How to update after aggregate in MongoDB?

To update documents after performing aggregation analysis in MongoDB, you cannot directly update within the aggregation pipeline. Instead, use the update() method with array filters to target specific array elements based on conditions.

Syntax

db.collection.update(
    { "field": value },
    { $inc: { "arrayField.$[identifier].field": incrementValue } },
    { arrayFilters: [{ "identifier.field": condition }] }
);

Sample Data

Let us first create a collection with documents ?

db.demo376.insertOne({
    "id": 101,
    "details": [
        {
            "Name": "Chris",
            "Age": 21,
            "Score": 45
        },
        {
            "Name": "David",
            "Age": 23,
            "Score": 67
        },
        {
            "Name": "Bob",
            "Age": 20,
            "Score": 54
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5a71b92ae06a1609a00b0d")
}

Display all documents from the collection ?

db.demo376.find().pretty();
{
    "_id": ObjectId("5e5a71b92ae06a1609a00b0d"),
    "id": 101,
    "details": [
        {
            "Name": "Chris",
            "Age": 21,
            "Score": 45
        },
        {
            "Name": "David",
            "Age": 23,
            "Score": 67
        },
        {
            "Name": "Bob",
            "Age": 20,
            "Score": 54
        }
    ]
}

Example: Update Array Elements with Conditions

Increment age by 3 for students aged 21 with scores greater than 40 ?

db.demo376.update(
    { "id": 101 },
    { $inc: { "details.$[d].Age": 3 } },
    { arrayFilters: [{ $and: [{ "d.Age": 21 }, { "d.Score": { "$gt": 40 } }] }] }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo376.find().pretty();
{
    "_id": ObjectId("5e5a71b92ae06a1609a00b0d"),
    "id": 101,
    "details": [
        {
            "Name": "Chris",
            "Age": 24,
            "Score": 45
        },
        {
            "Name": "David",
            "Age": 23,
            "Score": 67
        },
        {
            "Name": "Bob",
            "Age": 20,
            "Score": 54
        }
    ]
}

Key Points

  • Use $[identifier] positional operator to target specific array elements.
  • arrayFilters specify conditions for which array elements to update.
  • The identifier name (like d) can be any variable name you choose.

Conclusion

While aggregation pipelines cannot directly update documents, you can use update() with array filters to modify specific array elements based on complex conditions. This approach provides precise control over which nested elements to update.

Updated on: 2026-03-15T02:43:54+05:30

712 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements