MongoDB 聚合框架没有保留用 $addFields 添加的内容 [英] MongoDB aggregate framework not keeping what was added with $addFields

查看:24
本文介绍了MongoDB 聚合框架没有保留用 $addFields 添加的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字段已添加但随后消失.这是 mongo shell 中的代码:

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 }

推荐答案

聚合仅读取集合中的数据;它也不会编辑集合.考虑聚合的最佳方式是读取一些数据并对其进行操作以供立即使用.

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.

如果您想在主源中更改它,则必须使用 update 方法.

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)
})

这篇关于MongoDB 聚合框架没有保留用 $addFields 添加的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆