其中对蒙戈阵列条款不起作用
问题描述:
我是新来的MongoDB,我有我的数据库如下文件:其中对蒙戈阵列条款不起作用
{“_id”:{“$ OID”:“546e916cd38e0b3e0e79592f”},“名“:”hamed“,”entity“:[”1“,”2“]}
现在我想阅读aal文档,该实体= [”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子句吗?
答
您需要将您的查询参数DBObject
。对于$in
运营商,您缺少DBObject
。
如果只想有两个“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();
}
答
$中应该是一个BasicDBObject还有:
DBObject oredrFields = new BasicDBObject();
DBObject inOp = new BasicDBObject();
inOp .put("$in", new String[]{"1","2"});
oredrFields.put("entity", inOp);