Java MongoDB gets value for additional document

I am trying to get the key value from a subdocument, and I cannot figure out how to use the BasicDBObject.get () function, since the key is built into two levels. Here is the structure of the document

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

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

+5
source share
4 answers

You must first get the report object, and then access its contents. You can see the sample code 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);
}
+10
source

, ( , ).

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

query = (BasicDBObject) cursor.next()

+3

You can try this, it worked for me

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

+1
source

You can also use queries, as is the case with MongoTemplate, etc.

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

All Articles