Apply a condition inside subset in MongoDB Aggregation?

To apply a condition inside subset in MongoDB aggregation, use $setIsSubset. This operator checks whether a specified set is a subset of another set, returning true if all elements exist in the target array.

Syntax

{
    $setIsSubset: [<expression1>, <expression2>]
}

Sample Data

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

Display all documents in the collection:

db.subsetDemo.find().pretty();
{
    "_id": ObjectId("5e063e49150ee0e76c06a052"),
    "StudentName": "Chris",
    "StudentFavouriteSubject": [
        "Java",
        "Python"
    ]
}
{
    "_id": ObjectId("5e063e4f150ee0e76c06a053"),
    "StudentName": "Chris",
    "StudentFavouriteSubject": [
        "Java",
        "Python",
        "MySQL"
    ]
}

Example

Check if "MySQL" exists in each student's favourite subjects using $setIsSubset:

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

Key Points

  • $setIsSubset compares two arrays and returns true if the first array is a subset of the second.
  • The first parameter ["MySQL"] is the subset to check for.
  • The second parameter "$StudentFavouriteSubject" is the field containing the superset array.

Conclusion

Use $setIsSubset in MongoDB aggregation to conditionally check if specific values exist within array fields. This operator is particularly useful for filtering documents based on array content membership.

Updated on: 2026-03-15T01:48:15+05:30

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements