Java中mongodb使用and和or的复合查询
在MongoDB的JAVA查询中对应这些问题
and查询
1 //条件 startsAt< curr and endsAt > curr2 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 查询
1 //条件是startsAt < curr or endsAt>curr2 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);
以上是 Java中mongodb使用and和or的复合查询 的全部内容, 来源链接: utcz.com/z/394101.html