MongoDB Java - Fetching id in nested json -


i have following json structure. trying retreive run following mongo query in java hdata._id not null.

mongodb query: db.collection.find({},{"hdata._id":1, "hdata.createdby":1} )  {     "_id" : objectid("55567e594e3256a23565ce58"),        "hdata" : {         "isdeleted" : false,         "candelete" : false,         "canupdate" : false,         "createdby" : “xyz”,         "createddate" : "2015-05-15t15:05:30",         "_id" : "7"     },     "changedate" : "2015-02-19t16:02:12",  } 

the code have written in java fetch hdata._id is

mongocursor<document> cur = col.find(new basicdbobject("hdata._id", new basicdbobject("$ne",null)))).iterator();         try{             while(cur.hasnext()){                 system.out.println(cur.next().getobjectid("hdata._id"));                 i++;             }         }finally {             cur.close();         } 

however, hdata._id returned null. me ?

you can't nested properties using dot notation, e.g. x.y.

so in example need hdata first, call on _id. this:

    mongocursor<document> cur = col.find(new basicdbobject("hdata._id", new basicdbobject("$ne",null))).iterator();      while(cur.hasnext()){         system.out.println(cur.next().get("hdata", document.class).getstring("_id"));     } 

also note in example hdata._id shown string , not objectid, hence in example i've used getstring().

edit since sounds may have mixed types hdata._id here's more robust example type checking , debug output illustrate:

    mongocursor<document> cur = col.find(new basicdbobject("hdata._id", new basicdbobject("$ne",null))).iterator();      while(cur.hasnext()){         document doc = cur.next();         system.out.println("document _id" + doc.get("_id"));         document hdata = doc.get("hdata", document.class);         object id = hdata.get("_id");         system.out.println("hdata._id " + id);          // check type if need         if (id instanceof string) {             system.out.println("hdata._id string: " + id);         } else if (id instanceof objectid) {             system.out.println("hdata._id objectid: " + id);         } else {             system.out.println("hdata._id of type " + id.getclass().getname());         }     } 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -