Set condition in MongoDB nested document?



Let’s say we need to find a document with a value greater than specific value. For this, use dot notation in nested document and set the condition with $gt.

Let us see an example and create a collection with documents −

> db.demo688.insert( ... { ... information:{id:1,details:[ ...    {otherDetails:{ ...       values:75 ...       } ...    } ... ] ... } ... } ... ) WriteResult({ "nInserted" : 1 }) > db.demo688.insert({ ... information: ... { ... id:2, ... details: ... [ ...    {otherDetails:{ ...       values:78 ...    } ... } ... ] ... } ... } ... ) WriteResult({ "nInserted" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo688.find();

This will produce the following output −

{ "_id" : ObjectId("5ea57986a7e81adc6a0b3965"), "information" : { "id" : 1, "details" : [ { "otherDetails" : { "values" : 75 } } ] } } { "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

Following is the query to access MongoDB nested document −

> db.demo688.find({"information.details.otherDetails.values":{$gt:75}});

This will produce the following output −

{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }
Updated on: 2020-05-14T09:04:56+05:30

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements