How to project specific elements in an array field with MongoDB?

To project specific elements in an array field in MongoDB, use the $project stage with $filter to conditionally include array elements that match your criteria.

Syntax

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

Sample Data

db.demo355.insertOne({
    "id": 101,
    "details": [
        {"Name": "Chris", "isMarried": 1},
        {"Name": "David", "isMarried": 0},
        {"Name": "Mike", "isMarried": 1}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e568928f8647eb59e5620c5")
}

Display all documents from the collection ?

db.demo355.find().pretty();
{
    "_id": ObjectId("5e568928f8647eb59e5620c5"),
    "id": 101,
    "details": [
        {
            "Name": "Chris",
            "isMarried": 1
        },
        {
            "Name": "David",
            "isMarried": 0
        },
        {
            "Name": "Mike",
            "isMarried": 1
        }
    ]
}

Example: Filter Married Persons

Project only the array elements where isMarried equals 1 ?

db.demo355.aggregate([
    {
        $project: {
            details: {
                $filter: {
                    input: "$details",
                    as: "out",
                    cond: { $eq: ["$$out.isMarried", 1] }
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e568928f8647eb59e5620c5"),
    "details": [
        { "Name": "Chris", "isMarried": 1 },
        { "Name": "Mike", "isMarried": 1 }
    ]
}

Key Points

  • $filter returns only array elements that satisfy the condition.
  • Use $$variableName to reference the alias defined in the as field.
  • The $project stage reshapes the document structure.

Conclusion

The $project stage with $filter allows selective projection of array elements based on specific conditions. This approach efficiently filters array content while maintaining the document structure.

Updated on: 2026-03-15T02:36:05+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements