How to project specific elements in an array field with MongoDB?


To project-specific elements in an array field, use $project. Let us create a collection with documents −

>db.demo355.insertOne({"id":101,"details":[{"Name":"Chris",isMarried:1},{"Name":"David",isMarried:0},{"Name":"Mike",isMarried:1}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e568928f8647eb59e5620c5")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e568928f8647eb59e5620c5"),
   "id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "isMarried" : 1
      },
      {
         "Name" : "David",
         "isMarried" : 0
      },
      {
         "Name" : "Mike",
         "isMarried" : 1
      }
   ]
}

Following is the query to project-specific elements in an array field −

> db.demo355.aggregate([
...    {
...       $project: {
...          details: {
...             $filter: {
...                input: "$details",
...                as: "out",
...                cond: { $eq:["$$out.isMarried",1] }
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{
   "_id" : ObjectId("5e568928f8647eb59e5620c5"), "details" : [
      { "Name" : "Chris", "isMarried" : 1 },
      { "Name" : "Mike", "isMarried" : 1 }
   ] 
}

Updated on: 02-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements