MongoDB query to add matched key to list after query?

To add matched elements to a list after querying in MongoDB, use the $filter operator within an aggregation pipeline. This allows you to filter array elements based on specific conditions and return only the matching elements.

Syntax

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

Sample Data

db.demo334.insertOne({
    "Name": "Chris",
    "Age": 21,
    "details": [
        {
            "Subject": "MySQL",
            "Score": 78
        },
        {
            "Subject": "MongoDB",
            "Score": 45
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e52241bf8647eb59e562090")
}

Display the document ?

db.demo334.find().pretty();
{
    "_id": ObjectId("5e52241bf8647eb59e562090"),
    "Name": "Chris",
    "Age": 21,
    "details": [
        {
            "Subject": "MySQL",
            "Score": 78
        },
        {
            "Subject": "MongoDB",
            "Score": 45
        }
    ]
}

Example: Filter High Scores

Add only subjects with scores >= 70 to the filtered list ?

db.demo334.aggregate([
    {
        $addFields: {
            details: {
                $filter: {
                    input: "$details",
                    as: "out",
                    cond: { $gte: ["$$out.Score", 70] }
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e52241bf8647eb59e562090"),
    "Name": "Chris",
    "Age": 21,
    "details": [
        {
            "Subject": "MySQL",
            "Score": 78
        }
    ]
}

How It Works

  • $addFields creates or replaces the details field with filtered results
  • $filter processes each array element and applies the condition
  • $$out.Score references the Score field of each array element
  • Only elements meeting the condition ($gte: 70) are included in the output

Conclusion

Use $filter within $addFields to create filtered lists based on query conditions. This approach maintains the original document structure while returning only matched array elements.

Updated on: 2026-03-15T02:31:49+05:30

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements