2017-01-29 68 views
0

我正試圖將「nodes」數組中的所有元素加載到Java List或Hashmap中。如何在MongoDB中檢索/查找嵌套數組的所有元素Java

我正在處理特定的JSON格式,我無法修改。 Mongo DB集合僅包含一個文檔,該文檔如下所示。我試圖查詢「節點」數組的所有元素,但無法設法這樣做。

MongoCollection<Document> collection = mongoDB.getCollection(collectionName); 
BasicDBObject query = new BasicDBObject(); 
query.put("nodes", ""); 
List<Document> test2 = collection.find(query).into(new ArrayList<Document>()); 

Test2現在返回NULL。我知道我錯了,但不知道如何去做。 這裏是JSON

{ 
    "_id": "12123434", 
    "nodes": [ 
    { 
     "id": "1", 
     "name": "bla", 
     "attributes": [ 
     "string1", 
     "string2" 
     ] 
    }, 
    { 
     "id": "2", 
     "name": "blabla", 
     "attributes": [ 
     "string1", 
     "string2" 
     ] 
    } 
    ], 
    "groups": [] 
} 

回答

2

你只需要項目nodes和地圖。

import static com.mongodb.client.model.Projections.*; 

List<Document> nodes = (List<Document>) collection.find().projection(fields(include("nodes"), excludeId())).map(document -> document.get("nodes")).first(); 
+0

我不能得到方法include()和excludeId()被識別。我嘗試導入所有內容,但它仍然不起作用 – Storm

+0

將靜態導入添加到答案中。 – Veeram

+0

謝謝,完美的作品! – Storm

相關問題