MongoDB Aggregate Variable to create Multiple Fields?

拟墨画扇 提交于 2019-12-08 04:28:37

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/25047302/mongodb-aggregate-variable-to-create-multiple-fields

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