mongodb complex conditional query (or with and)

Category Column:  MongoDB

Disclaimer: This article is a blogger original article, follow the  CC 4.0 BY-SA  copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/tjbsl/article/details/80620303
Mongodb query requires the use of complex or stitching and parameters and
There MongoDb table:
1
"state1" : 11,
"state2" : 21,
"value" : 100
2
"state1" : 11,
"state2" : 22,
"value" : 300
3
"state1" : 11,
"state2" : 22,
"value" : 200
4
"state1" : 12,
"state2" : 21,
"value" : 300
 
To achieve the management of data in the form of the following SQL:
Relational Database: select * from where (state1 = 11 and state2 = 22) or value> 300
The first to use MongoDB query ways:
Divided into the following steps to achieve:
Step a: implement (state1 = 11 and state2 = 22)
db.getCollection('testOrAnd').find(
{$and:[{"state1":11},{"state2":22}]}
)
Step 2: Using or forms of implementing the value> 300
db.getCollection('testOrAnd'). find(
{ $or:[{"value":{$gte:300}}] }
)
Step 3: the step of splicing parameters to a two step or conditions
db.getCollection('testOrAnd').
find({$or:
[
{$and:[{"state1":11},{"state2":22}]},{"value":{$gte:300}}
]
})
 
Ultimately result:
 
Use spring-mongotemplate way to query (Criteria.where a static method):
Query analysis, a similar analysis using client mode, divided into the following steps to achieve:
Step a: implement (state1 = 11 and state2 = 22)
query.addCriteria(
new Criteria().andOperator(
Criteria.where("state1").is(11),
Criteria.where("state2").is(22)
)
);
Step 2: Using or forms of implementing the value> 300
query.addCriteria(
new Criteria().orOperator(
Criteria.where("value").gte(300)
)
);
步骤三:将步骤一参数拼接到步骤二or条件
query.addCriteria(
new Criteria().orOperator(
Criteria.where("value").gte(300),
new Criteria().andOperator(
Criteria.where("state1").is(11),
Criteria.where("state2").is(22)
)
)
);
 
升级查询,实际场景中要根据传输的参数是否为空,拼接查询条件:
(1)如果最外层是and关系(query.add多个creterria默认为and关系)
if(条件){
query.addCriteria(Criteria.where);
}
if(条件){
query.addCriteria(Criteria.where);
}
if(条件){
query.addCriteria(Criteria.where);
}
默认拼接的query条件为and形式。
(1)如果最外层是or关系(目前只想到此笨方法)
//1.拼接参数
Criteria operator1=null;
Criteria operator2=null;
if(1==1){//模拟判断条件
operator1 = new Criteria().andOperator(
Criteria.where("state1").is(11),
Criteria.where("state2").is(22)
);
}
if(1==1){//模拟判断条件
operator2 = Criteria.where("value").gte(300);
}
//2.判断参数
if(operator1!=null && operator2!=null){
query.addCriteria(new Criteria().orOperator(operator1,operator2));
}else if(operator1!=null){
query.addCriteria(operator1);
}else if(operator2!=null){
query.addCriteria(operator2);
}
 
补充:多个条件直接查询,默认是and形式
db.getCollection('testOrAnd').find({"state1":11,"state2":22})
即query.add多个creterria默认为and关系
 
 

Guess you like

Origin www.cnblogs.com/kelelipeng/p/12010554.html