How to use arrays as filters by querying subdocuments in MongoDB?

To use arrays as filters when querying subdocuments in MongoDB, use the $setIsSubset operator within an aggregation pipeline. This operator checks if one array is a subset of another, making it useful for filtering array elements based on specific values.

Syntax

db.collection.aggregate([
    { $project: {
        "arrayField": {
            $filter: {
                input: "$arrayField",
                as: "item",
                cond: { $setIsSubset: [["$$item.field"], [filterValues]] }
            }
        }
    }}
]);

Sample Data

db.demo407.insertMany([
    {
        "Name": "Chris",
        "details": [
            { "id": 100 },
            { "id": 110 },
            { "id": 130 }
        ]
    },
    {
        "Name": "John", 
        "details": [
            { "id": 120 },
            { "id": 140 },
            { "id": 100 }
        ]
    }
]);

View Sample Data

db.demo407.find();
[
    {
        "_id": ObjectId("5e70dffe15dc524f70227677"),
        "Name": "Chris",
        "details": [
            { "id": 100 },
            { "id": 110 },
            { "id": 130 }
        ]
    },
    {
        "_id": ObjectId("5e70dffe15dc524f70227678"),
        "Name": "John",
        "details": [
            { "id": 120 },
            { "id": 140 },
            { "id": 100 }
        ]
    }
]

Example: Filter Subdocuments by ID Values

Filter documents to show only subdocuments with IDs 100 or 130 ?

db.demo407.aggregate([
    { $match: {} },
    { $project: {
        "Name": 1,
        "details": {
            $filter: {
                input: "$details",
                as: "output",
                cond: { $setIsSubset: [["$$output.id"], [100, 130]] }
            }
        }
    }}
]);
[
    {
        "_id": ObjectId("5e70dffe15dc524f70227677"),
        "Name": "Chris",
        "details": [
            { "id": 100 },
            { "id": 130 }
        ]
    },
    {
        "_id": ObjectId("5e70dffe15dc524f70227678"),
        "Name": "John", 
        "details": [
            { "id": 100 }
        ]
    }
]

How It Works

  • $filter processes each element in the details array
  • $setIsSubset checks if the subdocument's ID exists in the filter array [100, 130]
  • Only matching subdocuments are included in the result
  • The $$output.id reference accesses each subdocument's id field

Conclusion

Use $setIsSubset with $filter in aggregation pipelines to filter subdocuments based on array values. This approach efficiently queries nested documents while preserving the document structure.

Updated on: 2026-03-15T02:52:56+05:30

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements