Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregate framework not keeping what was added with $addFields

Field is added but then disappears. Here is the code from within the mongo shell:

> db.users.aggregate([{$addFields:{totalAge:{$sum:"$age"}}}])
{ "_id" : ObjectId("5acb81b53306361018814849"), "name" : "A", "age" : 1, "totalAge" : 1 }
{ "_id" : ObjectId("5acb81b5330636101881484a"), "name" : "B", "age" : 2, "totalAge" : 2 }
{ "_id" : ObjectId("5acb81b5330636101881484b"), "name" : "C", "age" : 3, "totalAge" : 3 }
> db.users.find().pretty()
{ "_id" : ObjectId("5acb81b53306361018814849"), "name" : "A", "age" : 1 }
{ "_id" : ObjectId("5acb81b5330636101881484a"), "name" : "B", "age" : 2 }
{ "_id" : ObjectId("5acb81b5330636101881484b"), "name" : "C", "age" : 3 }
like image 416
user2672224 Avatar asked Jan 25 '26 10:01

user2672224


1 Answers

Aggregation only reads data from your collection; it does not edit the collection too. The best way to think about aggregation is that you read some data and manipulate it for your immediate usage.

If you want change it in main source then you must use the update method.

Or an easier way (Not best but easy)

db.users.aggregate([{$addFields:{totalAge:{$sum:"$age"}}}]).forEach(function (x){
    db.users.save(x)
})
like image 69
Nozar Safari Avatar answered Jan 27 '26 00:01

Nozar Safari