Java中mongodb使用and和or的複合查詢

 在MongoDB的JAVA查詢中對應這些問題

and查詢
1  //條件 startsAt< curr  and endsAt > curr
2 long curr = new Date().getTime()/1000;
3         DBObject query = new BasicDBObject();
4         query.put("startsAt",new BasicDBObject("$lte", curr));
5         query.put("endsAt",new BasicDBObject("$gte", curr));

  or 查詢java

1  //條件是startsAt < curr or endsAt>curr
2  BasicDBObject autoEnd = new BasicDBObject();
3          BasicDBList condList = new BasicDBList();
4           condList.add(new BasicDBObject("startsAt", new BasicDBObject("$lte", curr)));
5           condList.add(new BasicDBObject("endsAt", new BasicDBObject("$gte", curr)));
6         autoEnd.put("$or",condList);

 


這是複合查詢
 1  //條件相似:project="H" and (startsAt<curr or endsAt>curr)
 2      
 3    BasicDBObject basicDBObject = new BasicDBObject();
 4 
 5         BasicDBList endList = new BasicDBList();
 6         BasicDBObject forceEnd = new BasicDBObject();
 7         forceEnd.put("project","H");
 8 
 9         BasicDBObject autoEnd = new BasicDBObject();
10         BasicDBList condList = new BasicDBList();
11         condList.add(new BasicDBObject("startsAt", new BasicDBObject("$lte", curr)));
12         condList.add(new BasicDBObject("endsAt", new BasicDBObject("$gte", curr)));
13         autoEnd.put("$or",condList);
14 
15         endList.add(forceEnd);
16         endList.add(autoEnd);
17 
18         basicDBObject.put("$and",endList);
19 
20         DBCursor cursor = mongoTemplate.getCollection("數據庫表名").find(basicDBObject);
相關文章
相關標籤/搜索