【发布时间】:2021-12-31 08:27:30
【问题描述】:
我对在 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 作为输出。
【问题讨论】: