Write a MongoDB query to get nested value?


You can use dot notation to get nested value. Let us first create a collection with documents

> db.nestedQueryDemo.insertOne(
...    {
...
...       "EmployeeName" : "John",
...       "EmployeeDetails" :
...       {
...
...          "_id":"EMP-101",
...          "EmployeeAge":23,
...          "EmployeeCompanyName":"IBM"
...
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea31dd628fa4220163b69")
}
> db.nestedQueryDemo.insertOne(
...    {
...
...       "EmployeeName" : "Carol",
...       "EmployeeDetails" :
...       {
...
...          "_id":"EMP-110",
...          "EmployeeAge":29,
...          "EmployeeCompanyName":"Amazon"
...
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ea36bd628fa4220163b6a")
}

Following is the query to display all documents from a collection with the help of find() method

> db.nestedQueryDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9ea31dd628fa4220163b69"),
   "EmployeeName" : "John",
   "EmployeeDetails" : {
      "_id" : "EMP-101",
      "EmployeeAge" : 23,
      "EmployeeCompanyName" : "IBM"
   }
}
{
   "_id" : ObjectId("5c9ea36bd628fa4220163b6a"),
   "EmployeeName" : "Carol",
   "EmployeeDetails" : {
      "_id" : "EMP-110",
      "EmployeeAge" : 29,
      "EmployeeCompanyName" : "Amazon"
   }
}

Following is the query for MongoDB nested value query

> db.nestedQueryDemo.find({"EmployeeDetails._id":"EMP-110"}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9ea36bd628fa4220163b6a"),
   "EmployeeName" : "Carol",
   "EmployeeDetails" : {
      "_id" : "EMP-110",
      "EmployeeAge" : 29,
      "EmployeeCompanyName" : "Amazon"
   }
}

Updated on: 30-Jul-2019

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements