Write a MongoDB query to get nested value?

MongoDBDatabaseBig Data Analytics

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"
   }
}
raja
Published on 12-Apr-2019 08:19:51
Advertisements