How to project specific fields from a document inside an array in Mongodb?

MongoDBDatabaseBig Data Analytics

To project specific fields from a document inside an array, you can use positional ($) operator.

Let us first create a collection with documents

> db.projectSpecificFieldDemo.insertOne(
   ... {
      ... "UniqueId": 101,
      ... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"},
         ... {"StudentName" : "Robert", "StudentCountryName" : "UK"},
      ... ]
      ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2")
}
> db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" :
   [{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David",
   "StudentCountryName" : "AUS"}, ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca27b106304881c5ce84ba3")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
   "UniqueId" : 101,
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentCountryName " : "US"
      },
      {
         "StudentName" : "Robert",
         "StudentCountryName" : "UK"
      }
   ]
}
{
   "_id" : ObjectId("5ca27b106304881c5ce84ba3"),
   "UniqueId" : 102,
   "StudentDetails" : [
      {
         "StudentName" : "Robert",
         "StudentCountryName " : "UK"
      },
      {
         "StudentName" : "David",
         "StudentCountryName" : "AUS"
      }
   ]
}

Following is the query to project specific fields from a document inside an array

> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentCountryName " : "US"
      }
   ]
}
raja
Published on 15-Apr-2019 07:32:19
Advertisements