1.再网上查询资料看到一种方法:先新建条件列表BasicDBList,然后将多个BasicDBObject再add进List程序如下
- 条件列表:
- BasicDBList condList = new BasicDBList();
- //年龄大于1小于100
- BasicDBObject cond1= new BasicDBObject();
- cond1.append("age",new BasicDBObject("$gt",1));
- cond1.append("age",new BasicDBObject("$lte",100));
- //性别为女
- BasicDBObject cond2= new BasicDBObject();
- cond2.append("sex","女");
- //将两个条件加入到条件集合中(多条件)
- condList.add(cond1);
- condList.add(cond2);
- BasicDBObject cond= new BasicDBObject();
- cond.put("$and", condList);
- 然后查询数据:
- DBCursor cursor= coll.find(cond);
在实际应用中发现一点问题,小于和大于两个范围查询是不能用一个cond存放的,会产生覆盖。应该将大于放在一个cond,小于放在一个cond中。
- 条件列表:
- BasicDBList condList = new BasicDBList();
- //年龄大于1小于100
- BasicDBObject cond1= new BasicDBObject();
- cond1.append("age",new BasicDBObject("$gt",1));
- BasicDBObject cond2= new BasicDBObject();
- cond2.append("age",new BasicDBObject("$lte",100));
- //性别为女
- BasicDBObject cond3= new BasicDBObject();
- cond3.append("sex","女");
- //将两个条件加入到条件集合中(多条件)
- condList.add(cond1);
- condList.add(cond2);
- condList.add(cond3);
- BasicDBObject cond= new BasicDBObject();
- cond.put("$and", condList);
- 然后查询数据:
- DBCursor cursor= dbCollection.find(cond);