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

MongoDBDatabaseBig Data Analytics

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 } ] }
raja
Published on 01-Jul-2020 10:27:35
Advertisements