我是mongodb的新手,我的数据库中有一个文件如下:
{“_ id”:{“$ oid”:“546e916cd38e0b3e0e79592f”},“name”:“hamed”,“entity”:[“1”,“2”]}
现在我想阅读实体= [“1”,“2”]的文档 为此,我尝试了以下代码:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("test");
Set<String> colls = db.getCollectionNames();
DBCollection coll = db.getCollection("test");
DBObject oredrFields = new BasicDBObject();
oredrFields.put("entity", ":{ $in: ['1', '2'] } }");
DBCursor cursor = coll.find(oredrFields);
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
但它没有返回任何内容......任何人都可以帮助我如何正确地编写我的where子句吗?
答案 0 :(得分:1)
$ in也应该是一个BasicDBObject:
DBObject oredrFields = new BasicDBObject();
DBObject inOp = new BasicDBObject();
inOp .put("$in", new String[]{"1","2"});
oredrFields.put("entity", inOp);
答案 1 :(得分:1)
您需要将查询参数作为DBObject
传递。您遗漏了DBObject
运营商的$in
。
如果您只想要同时包含“1”和“2”的记录,则需要使用$all
代替$in
,而entity
仅返回all
字段包含的文档 MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("test");
DBObject oredrFields = new BasicDBObject();
DBObject inQuery = new BasicDBObject().append("$all", new String[]{"1","2"});
oredrFields.put("entity", inQuery);
DBCursor cursor = coll.find(oredrFields);
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
传递的数组中的元素。
{{1}}