How to filter array in subdocument with MongoDB?

To filter elements within an array subdocument in MongoDB, you can use $unwind + $match in an aggregation pipeline, or the more concise $filter operator (MongoDB 3.2+).

Sample Data

db.filterArray.insertOne({
    "L": [{"N": 1}, {"N": 2}, {"N": 3}, {"N": 4}, {"N": 5}]
});

Method 1: Using $unwind + $match + $group

Unwind the array, filter matching elements, then regroup ?

db.filterArray.aggregate([
    { $match: { _id: ObjectId("5c6d63f2734e98fc0a434aeb") } },
    { $unwind: "$L" },
    { $match: { "L.N": { $gt: 3 } } },
    { $group: { _id: "$_id", subDocument: { $push: "$L.N" } } }
]).pretty();
{
    "_id": ObjectId("5c6d63f2734e98fc0a434aeb"),
    "subDocument": [4, 5]
}

$unwind flattens the array into individual documents. $match filters elements where N > 3. $group reassembles the matching values.

Method 2: Using $filter (Recommended)

The $filter operator is more efficient − no unwind/regroup needed ?

db.filterArray.aggregate([
    { $match: { _id: ObjectId("5c6d63f2734e98fc0a434aeb") } },
    {
        $project: {
            subDocument: {
                $filter: {
                    input: "$L",
                    as: "item",
                    cond: { $gt: ["$$item.N", 3] }
                }
            }
        }
    }
]).pretty();
{
    "_id": ObjectId("5c6d63f2734e98fc0a434aeb"),
    "subDocument": [{"N": 4}, {"N": 5}]
}

Comparison

Method Pros Cons
$unwind + $match Works on all MongoDB versions Slower; creates temp documents
$filter Faster, cleaner, no temp docs Requires MongoDB 3.2+

Conclusion

Use $filter in $project for efficient array filtering in subdocuments (MongoDB 3.2+). Fall back to $unwind + $match + $group for older versions or when you need more complex processing between the unwind and regroup stages.

Updated on: 2026-03-14T23:19:59+05:30

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements