【问题标题】:MongoDB Reading from Nested DocumentsMongoDB 从嵌套文档中读取
【发布时间】:2017-09-12 22:59:25
【问题描述】:

我有一个包含嵌套文档的文档,我认为根据过滤器我可以指定类似 data.sms.mobileNumber 的内容。然而,这是行不通的。

如何使用标准 Document getString 请求读取 data.sms.mobileNumber 字段中的数据?

示例文档:

{ "_id" : ObjectId("59b850bd81bacd0013d15085"), "data" : { "sms" : { "message" : "Your SMS Code is ABCDEFG", "mobileNumber" : "+447833477560" } }, "id" : "b0a3886d69fc7319dbb4f4cc21a6039b422810cd875956bfd681095aa65f6245" }

示例字段获取字符串请求:

document.getString("data.sms.message")

【问题讨论】:

    标签: java mongodb mongodb-java


    【解决方案1】:

    “路径”data.sms.message 指的是这样的结构:

    +- data
      |
      +- sms
        |
        +- message
    

    要使用 Java 驱动程序阅读此内容,您必须阅读 data 文档,然后是 sms 子文档,然后是该子文档的 message 属性。

    例如:

    Document data = collection.find(filter).first();
    Document sms = (Document) data.get("sms");
    String message = sms.getString("message");
    

    或者,与快捷方式相同:

    String message = collection.find(filter).first()
        .get("sms", Document.class)
        .getString("message");
    

    更新 1 回答这个问题:“我有一个案例,我在一个文档中有一个文档数组,我将如何从数组中的文档中获取一个字段?”假设您有一个包含名为details 的数组字段的文档,并且每个detail 都有nameage。像这样的:

    {"employee_id": "1", "details": [{"name":"A","age":"18"}]}
    {"employee_id": "2", "details": [{"name":"B","age":"21"}]}
    

    你可以像这样读取数组元素:

        Document firstElementInArray = collection.find(filter).first()
            // read the details as an Array 
            .get("details", ArrayList.class)
            // focus on the first element in the details array
            .get(0);
    
        String name = firstElementInArray.getString("name");
    

    【讨论】:

    • 非常感谢!我有一个文档中有一个文档数组的情况,我将如何从数组中的文档中获取一个字段?
    • @NathanEnglish 我已经用一个显示数组元素访问的示例更新了答案。
    • 谢谢!现在我看到它完全有道理。 :)
    猜你喜欢
    • 2018-03-09
    • 1970-01-01
    • 2021-11-12
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2016-08-04
    • 2021-02-25
    相关资源
    最近更新 更多