【问题标题】:How to get an item from an array inside Mongodb in javajava - 如何从Java中Mongodb中的数组中获取项目
【发布时间】: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 作为输出。

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    应该这样做:

    data.getList("likes", Map.class)
            .stream()
            .map(map -> map.get("comment"))
            .collect(Collectors.toList());
    

    我鼓励您阅读 Java 驱动程序的 Javadocs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      相关资源
      最近更新 更多