Syntax error How to only get the data of the nested JSON object in MongoDB?

How to only get the data of the nested JSON object in MongoDB?



To get the data of the nested JSON object in MongoDB, use findOne(). Let us create a collection with documents −

> db.demo109.insertOne(
...    {
...       "Name" : "Chris",
...       "Subjects" : [
...          {
...             "Id" : "100",
...             "Name":"MySQL",
...             "InstructorDetails" : [
...                {
...                   "Name" : "John"
...                }
...             ]
...          },
...          {
...             "Id" : "101",
...             "Name":"MongoDB",
...             "InstructorDetails" : [
...                {
...                   "Name" : "Mike"
...                }
...             ]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2ee7df9fd5fd66da21447a")
}

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

> db.demo109.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"), "Name" : "Chris", "Subjects" : [
      { "Id" : "100", "Name" : "MySQL", "InstructorDetails" : [ { "Name" : "John" } ] },
      { "Id" : "101", "Name" : "MongoDB", "InstructorDetails" : [ { "Name" : "Mike" } ] }
   ] 
}

Following is the query to only get the data of the nested JSON object in MongoDB −

> db.demo109.findOne(
... { Name: "Chris"}
... , { 'Subjects': { $elemMatch:{'Id':"100"} } }
... , function (err, doc) { console.log(doc) });

This will produce the following output −

{
   "_id" : ObjectId("5e2ee7df9fd5fd66da21447a"),
   "Subjects" : [
      {
         "Id" : "100",
         "Name" : "MySQL",
         "InstructorDetails" : [
            {
               "Name" : "John"
            }
         ]
      }
   ]
}
Updated on: 2020-03-30T11:52:05+05:30

917 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements