2014-11-21 60 views
0

我是新來的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子句嗎?

回答

1

您需要將您的查詢參數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(); 
    } 
1

$中應該是一個BasicDBObject還有:

DBObject oredrFields = new BasicDBObject(); 
DBObject inOp = new BasicDBObject(); 
inOp .put("$in", new String[]{"1","2"}); 
oredrFields.put("entity", inOp);