Project specific array field in a MongoDB collection?


Let us first create a collection with documents −

> db.projectionAnElementDemo.insertOne(
...    {
...       "CustomerId":100,
...       "CustomerDetails": [
...          {
...             "CustomerName": "Chris",
...             "CustomerCountryName": "US"
...          },
...          {
...             "CustomerName": "Robert",
...             "CustomerCountryName": "UK"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd31c56b64f4b851c3a13ea")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd31c56b64f4b851c3a13ea"),
   "CustomerId" : 100,
   "CustomerDetails" : [
      {
         "CustomerName" : "Chris",
         "CustomerCountryName" : "US"
      },
      {
         "CustomerName" : "Robert",
         "CustomerCountryName" : "UK"
      }
   ]
}

Following is the query to project element in array field −

> db.projectionAnElementDemo.find({},{CustomerId:1, "CustomerDetails.CustomerName":1}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd31c56b64f4b851c3a13ea"),
   "CustomerId" : 100,
   "CustomerDetails" : [
      {
         "CustomerName" : "Chris"
      },
      {
         "CustomerName" : "Robert"
      }
   ]
}

Updated on: 30-Jul-2019

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements