如何使用其 java 驱动程序在 mongodb 中使用 'or' 和 'and' 操作?
How to use 'or' along with 'and' operation in mongodb using its java driver?
db.mycol.find(
{
"likes": { $gt: 10 },
$or: [
{"by": "tutorials point"},
{"title": "MongoDB Overview"}
]
}).pretty()
它的等效 java 代码是什么?
您可以尝试这样的操作:
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("likes", new BasicDBObject("$gt", 10))
BasicDBObject q1 = new BasicDBObject("by", "tutorials point");
BasicDBObject q2 = new BasicDBObject("title", "MongoDB Overview");
BasicDBList or = new BasicDBList();
or.add(q1);
or.add(q2);
BasicDBObject orQuery = new BasicDBObject("$or", or);
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(gtQuery);
obj.add(orQuery );
BasicDBObject andQuery = new BasicDBObject();
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor = mycol.find(andQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
db.mycol.find(
{
"likes": { $gt: 10 },
$or: [
{"by": "tutorials point"},
{"title": "MongoDB Overview"}
]
}).pretty()
它的等效 java 代码是什么?
您可以尝试这样的操作:
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("likes", new BasicDBObject("$gt", 10))
BasicDBObject q1 = new BasicDBObject("by", "tutorials point");
BasicDBObject q2 = new BasicDBObject("title", "MongoDB Overview");
BasicDBList or = new BasicDBList();
or.add(q1);
or.add(q2);
BasicDBObject orQuery = new BasicDBObject("$or", or);
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(gtQuery);
obj.add(orQuery );
BasicDBObject andQuery = new BasicDBObject();
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor = mycol.find(andQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}