Using addFields pipeline and run with the MongoDB filter operator

The $addFields pipeline stage combined with the $filter operator allows you to add new fields or modify existing ones by filtering array elements based on specific conditions.

Syntax

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

Sample Data

Let us first create a collection with documents ?

db.demo118.insertOne({
    "Id": "101",
    "Name": "Chris",
    "Subjects": [
        "MySQL",
        "MongoDB",
        "Java"
    ],
    "Details": [
        {
            "Name": "David",
            "S": "MongoDB"
        },
        {
            "Name": "Bob",
            "S": "Python"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2f0c0cd8f64a552dae6364")
}

Display all documents from a collection with the help of find() method ?

db.demo118.find();
{
    "_id": ObjectId("5e2f0c0cd8f64a552dae6364"),
    "Id": "101",
    "Name": "Chris",
    "Subjects": ["MySQL", "MongoDB", "Java"],
    "Details": [
        {"Name": "David", "S": "MongoDB"},
        {"Name": "Bob", "S": "Python"}
    ]
}

Example: Filter Details Based on Subjects

Following is the query to use $addFields pipeline to filter Details array elements that match values in the Subjects array ?

db.demo118.aggregate([
    {
        $addFields: {
            "Details": {
                $filter: {
                    input: "$Details",
                    as: "out",
                    cond: { $in: ["$$out.S", "$Subjects"] }
                }
            }
        }
    }
]).pretty();
{
    "_id": ObjectId("5e2f0c0cd8f64a552dae6364"),
    "Id": "101",
    "Name": "Chris",
    "Subjects": [
        "MySQL",
        "MongoDB",
        "Java"
    ],
    "Details": [
        {
            "Name": "David",
            "S": "MongoDB"
        }
    ]
}

How It Works

  • $addFields creates or replaces the existing "Details" field
  • $filter processes each element in the Details array
  • $in checks if the "S" field value exists in the Subjects array
  • Only matching elements (David with "MongoDB") are retained

Conclusion

The $addFields stage with $filter provides a powerful way to modify array fields by keeping only elements that meet specific criteria, enabling dynamic field transformations in aggregation pipelines.

Updated on: 2026-03-15T01:57:33+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements