问题描述
给出以下查询,使用$$ priceToInflationRatio帮助创建多个计算字段的最佳方法是什么?根据我对$ let的了解,它似乎仅适用于创建单个字段-我想在我的整个$ project部分中使用变量.有可能吗?
Given the following query, what is the best method to use $$priceToInflationRatio to help create multiple calculated fields? From what I have read on $let, it appears to only work for creating a single field -- I would like to use the variables across my entire $project section. Is that possible?
db.books.aggregate([
{$project: {
'priceInflationresult': {
$let: {
vars: {
'priceToInflationRatio': {
$multiply: [{'$divide': [{'$subtract': ['$price', 1]}, 5]}, 10]
}
},
in: {
'$cond': [
{'$gt': ['$price', 5]},
{'$mod': ['$$priceToInflationRatio', 1]},
1
]
},
}
}
}}
])
推荐答案
$let
表达式的in
部分是一个对象,因此它可以接受多个键,每个键都可以是一个用范围内的变量:
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 } }
请注意,这必将创建子文档,因为不允许使用顶级$ let表达式.您可以在另一个$ project阶段进行更改.
Note that this will necessarily create subdocuments as top-level $let expressions are not allowed. You can change this with another $project stage.
这篇关于MongoDB聚合变量来创建多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!