mixiul__
mixiul__

Reputation: 405

Find nested values in mongo 3 with java

I have a document in my mongo collection that looks like this:

{ 
  "timestamp": 1460442540,
  "page": "home",
  "misc": {
             "color": "red",
             "light": "off" 
          }
}

What I want to be able to do is return the value of misc.color when a certain condition is met on page.

This is what I have:

   //find my query match
   Document value = mongoDBService.getCollection(collectionName)
            .find(eq("page", "home")).first();

    //prints json described above
    LOG.info(value.toString());

    //prints "misc" subdocument
    LOG.info(value.get("misc").toString());

    //null pointer
    LOG.info(value.get("misc.color").toString());

Is there some way to handle the dot notation here that I am missing? Ideally I want this query to be dynamic so it can handle dot notation values and higher level values.

I am using mongodb-driver 3.4.2.

Upvotes: 0

Views: 1616

Answers (2)

You can try this:

BasicDBObject query = (BasicDBObject)(value.get("misc")).getString("color"); 

Upvotes: 1

s7vr
s7vr

Reputation: 75994

You can update your code to below.

Document value = mongoDBService.getCollection(collectionName)
            .find(eq("page", "home")).first();

LOG.info(value.get("misc", Document.class).getString("color"));

Upvotes: 3

Related Questions