代码之家  ›  专栏  ›  技术社区  ›  Nathan English

从嵌套文档读取MongoDB

  •  2
  • Nathan English  · 技术社区  · 7 年前

    我如何读取数据中的数据。短讯服务。mobileNumber字段,使用标准文档getString请求?

    示例文档:

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

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

    document.getString("data.sms.message")
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   glytching    7 年前

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

    +- data
      |
      +- sms
        |
        +- message
    

    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 name age

    {"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");
    
    推荐文章