Java MongoDB getting value for sub document

19,464

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

Solution 2

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

Solution 3

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()

Solution 4

You can try this, this worked for me

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

Share:
19,464
Dhruv
Author by

Dhruv

Updated on June 14, 2022

Comments

  • Dhruv
    Dhruv almost 2 years

    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.

  • Dhruv
    Dhruv over 11 years
    Will try this out. Thanks very much.
  • Parvin Gasimzade
    Parvin Gasimzade over 11 years
    This is the same as i wrote.Instead of two line they wrote query in single line.
  • splungebob
    splungebob about 7 years
    For querying fields in subdocuments, using this dot notation worked perfectly for me. Thanks.