Extract subarray value in MongoDB?


To extract the subarray value in MongoDB, you can use $elemMatch projection operator.

Let us first create a collection with documents −

> db.extractSubArrayDemo.insertOne(
...    {
...       _id: 101,
...       "clientName":"Larry",
...       "ClientDetails":
...       [
...          {
...             "ClientProjectName":"Online Game",
...             "DeveloperTeamSize": 10
...          },
...          {
...             "ClientProjectName":"Pig Dice Game",
...             "DeveloperTeamSize": 12
...          },
...          {
...             "ClientProjectName":"Web Student Tracker",
...             "DeveloperTeamSize": 11
...          }
...
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

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

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

This will produce the following output −

{
   "_id" : 101,
   "clientName" : "Larry",
   "ClientDetails" : [
      {
         "ClientProjectName" : "Online Game",
         "DeveloperTeamSize" : 10
      },
      {
         "ClientProjectName" : "Pig Dice Game",
         "DeveloperTeamSize" : 12
      },
      {
         "ClientProjectName" : "Web Student Tracker",
         "DeveloperTeamSize" : 11
      }
   ]
}

Following is the query to extract subarray value in MongoDB −

> db.extractSubArrayDemo.find({ '_id': 101 },{ _id: 0, ClientDetails:
   { $elemMatch: {ClientProjectName: 'Pig Dice Game' } }}).pretty();

This will produce the following output −

{
   "ClientDetails" : [
      {
         "ClientProjectName" : "Pig Dice Game",
         "DeveloperTeamSize" : 12
      }
   ]
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements