1. 程式人生 > >mongodb複雜條件查詢 (or與and)

mongodb複雜條件查詢 (or與and)

使用Mongodb查詢需要拼接複雜的or和and引數MongoDb有表格:
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
要實現管理資料的如下SQL形式:關係資料庫:select * from where(state1=11 and state2=22) or value >300首先使用MongoDB的方式查詢:分為以下幾個步驟實現:步驟一:實現 (state1=11 and state2=22)db.getCollection('testOrAnd').find( {$and:[{"state1":11},{"state2":22}]} )步驟二:使用or形式實現 value >300db.getCollection('testOrAnd'). find( { $or:[{"value":{$gte:300}}] } )步驟三:將步驟一引數拼接到步驟二or條件db.getCollection('testOrAnd'). find({$or: [ {$and:[{"state1":11},{"state2":22}]},{"value":{$gte:300}} ] })最終實現結果:
使用spring-mongotemplate的方式查詢(Criteria.where是靜態方法):分析查詢方式,類似使用client的分析方式,分為以下幾個步驟實現:步驟一:實現 (state1=11 and state2=22)query.addCriteria( new Criteria().andOperator( Criteria.where("state1").is(11), Criteria.where("state2").is(22) ) );步驟二:使用or形式實現 value >300query.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關係