Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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. -
arrayFiltersspecify 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.
Advertisements
