Java MongoDB为子文档获取价值 [英] Java MongoDB getting value for sub document

查看:160
本文介绍了Java MongoDB为子文档获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从子文档中获取键的值,而且由于该键被深深地嵌入了两个级别,因此我似乎无法弄清楚如何使用BasicDBObject.get()函数.这是文档的结构

I am trying to get the value of a key from a sub-document and I can't seem to figure out how to use the BasicDBObject.get() function since the key is embedded two levels deep. Here is the structure of the document

File { 
  name: file_1
    report: {
      name: report_1,
      group: RnD
    }
}

基本上,一个文件包含多个报告,我需要检索给定文件中所有报告的名称.我可以执行BasicDBObject.get("name")并且可以获取值"file_1",但是我该怎么做这样的BasicDBObject.get("report.name")呢?我试过了,但是没用.

Basically a file has multiple reports and I need to retrieve the names of all reports in a given file. I am able to do BasicDBObject.get("name") and I can get the value "file_1", but how do I do something like this BasicDBObject.get("report.name")? I tried that but it did not work.

推荐答案

您应该首先获取报告"对象,然后访问其内容.您可以在下面看到示例代码.

You should first get the "report" object and then access its contents.You can see the sample code in the below.

DBCursor cur = coll.find();

for (DBObject doc : cur) {
    String fileName = (String) doc.get("name");
    System.out.println(fileName);

    DBObject report = (BasicDBObject) doc.get("report");
    String reportName = (String) report.get("name");
    System.out.println(reportName);
}

这篇关于Java MongoDB为子文档获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆