查询嵌套文档和atrihute做变量(MongoDB Java Driver 3.2)

时间:2016-03-04 07:41:26

标签: java mongodb-java

我有以下数据,我正在尝试读取数据并在变量中分配每个数据,但无法获取info中的数据,仍然给我null或{{1 }和email

phone

在java代码

下面
    {
    "_id": ObjectId ( "56c570d904df6c51b463da54"),
    "Name": "John Smith"
    "Age": 31,
    "Info": {
        "Email", "john.smith@mail.com"
        "Phone", "+987654321"
    }
}

1 个答案:

答案 0 :(得分:2)

看起来很近!代码中有几个错误:

  1. Null更改为null
  2. 您无法查找嵌套键,例如:document.getString( "info.email")将无效。您应该将子文档分配给变量,然后尝试从中获取数据。
  3. 我还没有测试过,但我认为这样的事情会更好:

    findAll.forEach (new Block <Document> () {
        @Override
        public void apply (Document document) {
            String name = document.getString ("name")! = null? document.getString( "name") : "";
            int age = document.getInteger ( "age", 0);
    
            // Get the info subdocument
            Document info = document.get("info", Document.class);
            String email = "";
            String phone = "";
            if (info != null) {
              email = info.getString ("email")! = null? info.getString("email") : "";
              phone = info.getString ("phone")! = null? info.getString("phone") : "";
            }
            Costumer costumer = new Costumer (name, age, email, phone);
            System.out.println(costumer);
        }
    });
    

    希望有所帮助。