How to filter array elements in MongoDB?

To filter array elements in MongoDB, you can use the $setIntersection operator within the aggregation framework. This operator returns elements that exist in both the original array and your filter criteria array.

Syntax

db.collection.aggregate([
    { $project: {
        fieldName: {
            $setIntersection: ["$arrayField", [filterValues]]
        }
    }}
]);

Sample Data

db.filterArrayElementsDemo.insertOne({
    "Scores": [10, 45, 67, 78, 90, 98, 99, 92]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd2d582b64f4b851c3a13c8")
}

Display the document to verify the data ?

db.filterArrayElementsDemo.find().pretty();
{
    "_id": ObjectId("5cd2d582b64f4b851c3a13c8"),
    "Scores": [
        10,
        45,
        67,
        78,
        90,
        98,
        99,
        92
    ]
}

Example: Filter Specific Values

Filter the Scores array to return only values 10, 98, and 99 ?

db.filterArrayElementsDemo.aggregate([
    { $match: {
        _id: ObjectId("5cd2d582b64f4b851c3a13c8")
    }},
    { $project: {
        Scores: {
            $setIntersection: ["$Scores", [10, 98, 99]]
        }
    }}
]);
{ "_id": ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores": [10, 98, 99] }

Key Points

  • $setIntersection returns elements that exist in both arrays
  • The result maintains the order from the original array
  • Use $match to target specific documents before filtering

Conclusion

The $setIntersection operator provides an efficient way to filter array elements by finding common values between the original array and your filter criteria. This method works well for exact value matching within aggregation pipelines.

Updated on: 2026-03-15T01:04:39+05:30

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements