我對在 MongoDB 中創建應用程式完全陌生。所以我遇到了一個問題,我不確定如何從 Mongodb 的陣列內部檢索專案。下面是例子
{
"name": "Random Person",
"age": 22,
"address": "Address of the User",
"likes":[{
"like": 1,
"comment": "Comment of the User",
"description": "Some description"
},
{
"like": 2,
"comment": "Comment of the User",
"description": "Some description"
},
{
"like": 3,
"comment": "Comment of the User",
"description": "Some description"
},
]
}
所以我想要的預期結果如下
Name: Random Person
address: Address of the User
Comment: [Comment of the User, Comment of the User, Comment of the User] (Assuming we have different data at each index retrieved from Mongodb)
以下是代碼
MongoCursor<Document> cursor = collection.find().iterator();
Document data = null;
while(cursor.hasNext()) {
data = cursor.next();
String name = (String) data.get("name");
String address = (String) data.get("address");
data.get("likes"); // Not sure about this line
}
我試過使用 data.get("likes.comment"); 但它回傳 null 作為輸出。
uj5u.com熱心網友回復:
這應該這樣做:
data.getList("likes", Map.class)
.stream()
.map(map -> map.get("comment"))
.collect(Collectors.toList());
我鼓勵您閱讀Java 驅動程式的Javadocs。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400721.html
上一篇:對id欄位的子集進行分片
