其中对蒙戈阵列条款不起作用

问题描述:

我是新来的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);