MongoDB query to return specific fields from an array?


To return specific fields, use aggregate $project. Let us first create a collection with documents −

> db.returnSpecificFieldDemo.insertOne(
   {
      "StudentId":1,
      "StudentDetails": [
         {
            "StudentName":"Larry",
            "StudentAge":21,
            "StudentCountryName":"US"
         },
         {
            "StudentName":"Chris",
            "StudentAge":23,
            "StudentCountryName":"AUS"
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce23d3236e8b255a5eee943")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ce23d3236e8b255a5eee943"),
   "StudentId" : 1,
   "StudentDetails" : [
      {
         "StudentName" : "Larry",
         "StudentAge" : 21,
         "StudentCountryName" : "US"
      },
      {
         "StudentName" : "Chris",
         "StudentAge" : 23,
         "StudentCountryName" : "AUS"
      }
   ]
}

Following is the query to return specific fields from an array −

> db.returnSpecificFieldDemo.aggregate([{$project:{_id:0, StudentId:'$StudentId', StudentCountryName:{ $arrayElemAt: ['$StudentDetails.StudentCountryName',1] }}}]);

This will produce the following output −

{ "StudentId" : 1, "StudentCountryName" : "AUS" }
raja
Published on 14-Jun-2019 15:17:18
Advertisements