Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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
      }
   ]
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.