Java MongoDB getting value for sub document

自古美人都是妖i 提交于 2019-12-10 14:17:26

问题


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
    }
}

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.


回答1:


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);
}



回答2:


I found a second way of doing it, on another post (didnt save the link otherwise I would have included that).

(BasicDBObject)(query.get("report")).getString("name") 

where query = (BasicDBObject) cursor.next()




回答3:


You can also use queries, as in the case of MongoTemplate and so on...

Query query = new Query(Criteria.where("report.name").is("some value"));



回答4:


You can try this, this worked for me

BasicDBObject query = new BasicDBObject("report.name", "some value");



来源:https://stackoverflow.com/questions/12166573/java-mongodb-getting-value-for-sub-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!