2015-11-02 177 views
0

我是Mongodb的新手。我在mongodb中有以下數據集。Mongodb在java中查詢嵌套文檔

{ 
"_id": { 
    "$oid": "563644f44b17ca12886440a9" 
}, 
"data": [ 
    { 
     "uid": 1, 
     "character": " ", 
     "unicode": 32, 
     "color": -7309587 
    }, 
    { 
     "uid": 2, 
     "character": "!", 
     "unicode": 33, 
     "color": -8911704 
    }, 
    { 
     "uid": 3, 
     "character": "\"", 
     "unicode": 34, 
     "color": -1778539 
    } 

我想從_id和字符中檢索此字段的顏色。我無法執行查詢。

這就是我試過的。

DBObject clause1 = new BasicDBObject("_id",new ObjectId(KEY1)); 
       DBObject clause2 = new BasicDBObject("data.character",text[i]);  
       BasicDBList or = new BasicDBList(); 
       or.add(clause1); 
       or.add(clause2); 
       DBObject query = new BasicDBObject("$and", or); 

另外,我在尋找方法在mongodb-java中查詢3.0.0+ api有很多問題。有人可以幫忙嗎?

+1

作爲一個輸出,你只需要'data.color'作爲特定​​的'_id'&'data.character'。對? –

+0

是的,非常。 – Amriteya

+0

然後,我想你需要[展開](https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/)數據數組,並使用'$ match'和'$ projection'運算符來聚合你可以做到這一點。 –

回答

1
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017)); 
    MongoDatabase db = mongoClient.getDatabase("testDB"); 
    AggregateIterable<Document> iterable = db.getCollection("testCollection").aggregate(
      asList(new Document("$unwind", "$data"), new Document("$match", (new Document("_id", new ObjectId(
        "5636f106b2acf98ecb033b98")).append("data.character", " "))), new Document("$project", 
        new Document("data.color", 1).append("_id", 0)))); 

    iterable.forEach(new Block<Document>() 
    { 
     @Override 
     public void apply(final Document document) 
     { 
      System.out.println(document.toJson()); 
     } 
    }); 

有關詳情,請MongoDB Documentation

+0

我明白了。我在彙總收集方法方面遇到了很多麻煩。我正在使用3.0.0 java-mongo驅動程序api。顯然,他們已經改變了很多,它仍處於測試階段。非常感謝。 – Amriteya

+0

歡迎@Amriteya。 –

0

一個簡單的解決方案

在文檔中, OID是每個文檔的唯一鍵,因此您的查詢應該是這樣的

DBObject query = new BasicDBObject("_id.oid", KEY1); 
    // Query with value - DBObject query = new BasicDBObject("_id.oid","563644f44b17ca12886440a9"); 

    Assign this to a cursor as shown below 
    DBCollection coll = db.getCollection("mycollection"); 
    DBCursor cursor = coll.find(query); 
    Iterate the collection and retrieve your desired value. 
+0

我也通過_id獲得了id。 – Amriteya