Using $addFields pipeline and run with the MongoDB $filter operator


Let us first create a collection with documents −

> db.demo118.insertOne(
...    {
...       "Id" : "101",
...       "Name" : "Chris",
...       "Subjects" : [
...          "MySQL",
...          "MongoDB",
...          "Java"
...       ],
...       "Details" : [
...          {
...             "Name" : "David",
...             S:"MongoDB"
...          },
...          {
...             "Name" : "Bob",
...             S:"Python"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f0c0cd8f64a552dae6364")
}

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

> db.demo118.find();

This will produce the following output −

{ "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"), "Id" : "101", "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java" ], "Details" : [ { "Name" : "David", "S" : "MongoDB" }, { "Name" : "Bob", "S" : "Python" } ] }

Following is the query to use $addFields pipeline −

> db.demo118.aggregate([
...    {
...       "$addFields": {
...          "Details": {
...             "$filter": {
...                "input": "$Details",
...                "as": "out",
...                "cond": { "$in": ["$$out.S", "$Subjects"] }
...             }
...          }
...       }
...    }
... ]).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"),
   "Id" : "101",
   "Name" : "Chris",
   "Subjects" : [
      "MySQL",
      "MongoDB",
      "Java"
   ],
   "Details" : [
      {
         "Name" : "David",
         "S" : "MongoDB"
      }
   ]
}

Updated on: 30-Mar-2020

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements