Filter specific values from a MongoDB document

To filter specific values from a MongoDB document, use the $filter operator in aggregation pipelines. This operator allows you to select array elements that match specific conditions and return only those elements.

Syntax

{
    $filter: {
        input: "$arrayField",
        as: "variable",
        cond: { condition }
    }
}

Sample Data

db.demo751.insertOne({
    _id: 101,
    details: [
        { Name: "Robert", id: 110, Age: 21 },
        { Name: "Rae", id: 110, Age: 22 },
        { Name: "Ralph", id: 116, Age: 23 }
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Example 1: Filter by Specific ID Value

Filter documents where the id field equals 110 and get only the last matching element ?

db.demo751.aggregate([
    {
        $addFields: {
            details: {
                $let: {
                    vars: {
                        filtered: { 
                            $filter: { 
                                input: "$details", 
                                as: "out", 
                                cond: { $eq: ["$$out.id", 110] } 
                            } 
                        }
                    },
                    in: { $slice: ["$$filtered", -1] }
                }
            }
        }
    }
]);
{ "_id": 101, "details": [{ "Name": "Rae", "id": 110, "Age": 22 }] }

Example 2: Simple Filter Without $slice

Get all elements where id equals 110 ?

db.demo751.aggregate([
    {
        $addFields: {
            filteredDetails: {
                $filter: {
                    input: "$details",
                    as: "item",
                    cond: { $eq: ["$$item.id", 110] }
                }
            }
        }
    }
]);
{ 
    "_id": 101, 
    "details": [...], 
    "filteredDetails": [
        { "Name": "Robert", "id": 110, "Age": 21 },
        { "Name": "Rae", "id": 110, "Age": 22 }
    ] 
}

Key Points

  • $filter returns an array of matching elements based on the specified condition.
  • $slice can be used with $filter to get specific elements (first, last, etc.).
  • Use $$variable syntax to reference the iterator variable in conditions.

Conclusion

The $filter operator is essential for extracting specific array elements in MongoDB. Combine it with $slice for precise element selection or use it standalone to get all matching elements.

Updated on: 2026-03-15T03:56:18+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements