MongoDB Aggregate Variable to create Multiple Fields?

孤街浪徒 提交于 2019-12-06 15:03:26

The in part of a $let expression is an object, so it can accept multiple keys, each of which can be an expression that is evaluated with the variables in scope:

> db.test.insert({ "_id" : 0, "a" : 1, "b" : 1 })
> db.test.aggregate([{
    "$project" : {
        "test" : {
            "$let" : {
                "vars" : {
                    "c" : 2,
                    "d" : 3
                },
                "in": {
                    "a" : { "$add" : ["$a", "$$c"] },
                    "b" : { "$add" : ["$b", "$$d"] }
                }
            }
        }
    }
}]);
{ "_id" : 0, "test" : { "a" : 3, "b" : 4 } }

Note that this will necessarily create subdocuments as top-level $let expressions are not allowed. You can change this with another $project stage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!