Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java MongoDB getting value for sub document

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.

like image 597
Dhruv Avatar asked Aug 28 '12 19:08

Dhruv


2 Answers

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);
}
like image 152
Parvin Gasimzade Avatar answered Nov 09 '22 09:11

Parvin Gasimzade


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

like image 20
Dhruv Avatar answered Nov 09 '22 10:11

Dhruv