Querying on an array of objects for specific nested documents with MongoDB?


To query on an array of objects for nested documents, use find(). Let us create a collection with documents −

> db.demo763.insertOne(
...    {
...       _id:1,
...       CountryName:"US",
...       "studentInformation": [
...          {
...             StudentName:"Chris",
...          },
...          {
...             StudentName:"David",
...             StudentAge:22
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }

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

> db.demo763.find();

This will produce the following output −

{ "_id" : 1, "CountryName" : "US", "studentInformation" : [ { "StudentName" : "Chris" }, { "StudentName" : "David", "StudentAge" : 22 } ] }

Following is how to query an array of objects to fetch specific nested documents −

> db.demo763.find({},
... {
...    studentInformation: {
...       $elemMatch: {
...          StudentAge: {
...             $exists: true
...          }
...       }
...    }
... })

This will produce the following output −

{ "_id" : 1, "studentInformation" : [ { "StudentName" : "David", "StudentAge" : 22 } ] }

Updated on: 01-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements