Apply a condition inside subset in MongoDB Aggregation?


To apply a condition, use $setIsSubset. Let us first create a collection with documents −

> db.subsetDemo.insertOne({"StudentName":"Chris","StudentFavouriteSubject":["Java","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e063e49150ee0e76c06a052")
}
> db.subsetDemo.insertOne({"StudentName":"Chris","StudentFavouriteSubject":["Java","Python","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e063e4f150ee0e76c06a053")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e063e49150ee0e76c06a052"),
   "StudentName" : "Chris",
   "StudentFavouriteSubject" : [
      "Java",
      "Python"
   ]
}
{
   "_id" : ObjectId("5e063e4f150ee0e76c06a053"),
   "StudentName" : "Chris",
   "StudentFavouriteSubject" : [
      "Java",
      "Python",
      "MySQL"
   ]
}

Here is the query to apply condition inside subset in MongoDB aggregation −

> db.subsetDemo.aggregate([
...    {
...       $project: {
...          _id: 0,
...          StudentName: 1,
...          isMySQL: {
...             $setIsSubset: [["MySQL"], "$StudentFavouriteSubject"]
...          }
...       }
...    }
... ]);

This will produce the following output −

{ "StudentName" : "Chris", "isMySQL" : false }
{ "StudentName" : "Chris", "isMySQL" : true }

Updated on: 27-Mar-2020

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements