How would I filter out sub documents in MongoDB?

To filter out sub documents in MongoDB, use the aggregation pipeline with $unwind to deconstruct array elements and $match to apply filtering conditions on the individual sub documents.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $match: { "arrayField.field": { $operator: value } } }
]);

Sample Data

db.demo662.insertOne({
    "details": [
        {
            "Name": "Chris",
            "Marks": 35
        },
        {
            "Name": "Bob", 
            "Marks": 45
        },
        {
            "Name": "David",
            "Marks": 30
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ea1b2be24113ea5458c7d04")
}

Display all documents from the collection ?

db.demo662.find();
{ 
    "_id": ObjectId("5ea1b2be24113ea5458c7d04"), 
    "details": [ 
        { "Name": "Chris", "Marks": 35 }, 
        { "Name": "Bob", "Marks": 45 }, 
        { "Name": "David", "Marks": 30 } 
    ] 
}

Example: Filter Sub Documents with Marks > 40

db.demo662.aggregate([
    { $unwind: "$details" },
    { $match: { "details.Marks": { $gt: 40 } } }
]);
{ 
    "_id": ObjectId("5ea1b2be24113ea5458c7d04"), 
    "details": { "Name": "Bob", "Marks": 45 } 
}

How It Works

  • $unwind creates separate documents for each array element
  • $match filters the unwound documents based on specified conditions
  • Only sub documents meeting the criteria are returned in the final result

Conclusion

Use $unwind followed by $match in the aggregation pipeline to effectively filter sub documents. This approach transforms array elements into individual documents for precise filtering based on nested field values.

Updated on: 2026-03-15T03:26:21+05:30

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements