mongo java中and、or多條件查詢
阿新 • • 發佈:2018-12-24
//and、or多條件聯合查詢
//age條件(and條件)
BasicDBList condList = new BasicDBList();
BasicDBObject cond = new BasicDBObject();
cond.put("$gt",0);
cond.put("$lte",40);
BasicDBObject composeCod = new BasicDBObject();
composeCod.put("age", cond);
condList.add(composeCod);
//name條件
BasicDBObject nameCond = new BasicDBObject();
nameCond.put("name", "name");
condList.add(nameCond);
//查詢條件組合(or條件)
BasicDBObject searchCond = new BasicDBObject();
searchCond.put("$or", condList);
DBCursor findRefResult = coll.find(searchCond);
int i=1;
while (findRefResult.hasNext()) {
System.out.println("Inserted Document: "+i);
System.out.println(findRefResult.next());
i++;
//age條件(and條件)
BasicDBList condList = new BasicDBList();
BasicDBObject cond = new BasicDBObject();
cond.put("$gt",0);
cond.put("$lte",40);
BasicDBObject composeCod = new BasicDBObject();
composeCod.put("age", cond);
condList.add(composeCod);
//name條件
BasicDBObject nameCond = new BasicDBObject();
nameCond.put("name", "name");
condList.add(nameCond);
//查詢條件組合(or條件)
BasicDBObject searchCond = new BasicDBObject();
searchCond.put("$or", condList);
DBCursor findRefResult = coll.find(searchCond);
int i=1;
while (findRefResult.hasNext()) {
System.out.println("Inserted Document: "+i);
System.out.println(findRefResult.next());
i++;
}
//排序操作
DBCursor cursor = collection.find(filter_dbobject).limit(10).sort(new BasicDBObject("create_time",-1));