MongoDB in Java: Search for a value in a nested entry

Given the MongoDB entry below, how do we search for “occupation: doctor”?

{
"name" : Maren,
"age" : 29,
"details" : {
 address : "Geronimo Road"
 occupation: "doctor"
 }
}

{
"name" : Skoo,
"age" : 35, 
"details" : {
 address : "West Village, Hudensta"
 occupation: "warrior"
 }
}

{
"name" : Doby,
"age : 31,
"details" : {
 address : "99 Jump Street"
 occupation: "doctor"
 }
}

The result should give us the complete data for “Maren” and “Doby”.
“Skoo” should not appear in the search result.

Solution:
In MongoDB Java, accessing data inside a nested object must be accessed using the “details” key. We must first know the “details” key in order for us to access the “address” and “occupation” keys, which is under the root object. The Java code solution is provided as follows.

BasicDBObject searchCriteria = new BasicDBObject();
		
searchCriteria.put("details.occupation", "doctor");
DBObject result = collection.findOne(searchCriteria);
		
System.out.println(result);

Credits to this blog post below, I got the idea here:
http://rstechjournal.blogspot.com/2012/09/mongodb-search-nested-value-with-java.html

Advertisements

2 thoughts on “MongoDB in Java: Search for a value in a nested entry

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s