MongoDB retrieves values โ€‹โ€‹from BasicDBObject (Java)

I'm having trouble retrieving values โ€‹โ€‹from the requested documents in MongoDB.

For example, the structure of the document is similar:

{ "_id": { "$oid": "50f93b74f9eccc540b302462" }, "response": { "result": { "code": "1000", "msg": "Command completed successfully" }, "resData": { "domain:infData": { "domain:name": "ritesh.com", "domain:crDate": "2007-06-15T12:02:36.0000Z", "domain:exDate": "2013-06-15T12:02:36.0000Z" } } } } 

And request code:

  DBCollection collection = db.getCollection("domains"); BasicDBObject p = new BasicDBObject("response.resData.domain:infData.domain:name", "ritesh.com"); DBCursor c = collection.find(p); while(c.hasNext()) { DBObject obj = c.next(); Object value = obj.get("response.resData.domain:infData.domain:name"); } 

It queries and retrieves the document, but I cannot figure out how to extract the value of "response.resData.domain: infData.domain: name" or other similar nested values โ€‹โ€‹from DBObject (or BasicDBObject since c.next () returns the type BasicDBObject).

I could get objects one at a time, for example:

  ((DBObject)obj.get("response")).get("resData").... 

but it seems very cumbersome.

I thought, since you can put () the value of a nested field in BasicDBObject, for example:

  basicDBObject.put("response.resData.domain:infData.domain:name", "ritesh.com"); 

so that I can use get () in the same way to extract from a BasicDBObject result using the same key. As I tried to do in the code above:

  Object value = obj.get("response.resData.domain:infData.domain:name"); 

But this returns a null value.

This is probably something direct, but I can not understand it. And wherever I checked on the network, examples only extract values โ€‹โ€‹that are not nested from the result. how

  doc.get("name"); 

instead of something like:

  doc.get("name.lastname.clanname"); 

Any help would be greatly appreciated. Thanks!

+6
source share
2 answers

It is not possible to bind the property name as you do using the Java driver ( get and, accordingly, put should not work either).

You will need to get the objects one at a time, as you suggested.

 ((DBObject)obj.get("response")).get("resData") 

See here for a potential future function that will allow your syntax to work (although probably with a new method name).

+11
source

I ran into the same problem and I wrote a small function to get the bound properties.

 private Object getFieldFromCursor(DBObject o, String fieldName) { final String[] fieldParts = StringUtils.split(fieldName, '.'); int i = 1; Object val = o.get(fieldParts[0]); while(i < fieldParts.length && val instanceof DBObject) { val = ((DBObject)val).get(fieldParts[i]); i++; } return val; } 

Hope this helps.

+6
source

All Articles