如何使用Java检索Mongo DB文档中嵌套对象的值

时间:2020-08-24 10:05:54

标签: mongodb mongodb-java

我有一个如下文件:

"application" : "test",
"QA1" : {
    "url" : "https://google.co.in",
    "db" : {
        "userName" : "user",
        "password" : "pswd"
    }
}

我想通过调用键“ url”来检索值“ https://google.co.in”。

虽然使用下面的shell命令,但是我能够按预期检索值。 db.getCollection('Application_Data')。findOne({“ application”:“ test”})。QA1.url

但是当我将其转换为Java代码时,它会抛出空指针异常:

cursor = collection.find(Filters.eq("application","test")).iterator();
        while (cursor.hasNext()) {
            value=cursor.next().get("QA1.url").toString();
            break;
        }

我还尝试了如下所示的投影以获得所需的值:

cursor = collection.find(Filters.and(Filters.eq("application","test"))).projection(Projections.fields(Projections.include("QA1.url"),Projections.excludeId())).iterator();
        while (cursor.hasNext()) {
            System.out.println(cursor.next().get("QA1").toString());
        }

这给了我如下输出:

文档{{url = https://google.co.in}}

它仍然没有给我确切的价值。感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

Mongodb文档是嵌套的。如此说,在您的示例中,当您执行cursor.next().get("QA1")时,将在“ QA1”属性下获得文档。

因此,实现所需目标的方法是 cursor.next().get("QA1").get("url")。通过适当的错误处理(请考虑例外)。

一种更好的方法是使用像spring-data-mongodb这样的映射器,它将自动将mongodb的JSON响应映射到Java对象中。

答案 1 :(得分:0)

您需要使用Document类的getEmbedded方法来提取嵌套字段的值。

while (cursor.hasNext()) {
    Document doc = cursor.next();
    System.out.println(doc.toJson());
    String urlValue = doc.getEmbedded(Arrays.asList("QA1","url"), String.class);
    System.out.println(urlValue);  // output below
}

结果符合预期-字符串:https://google.co.in