【发布时间】:2021-07-24 04:13:00
【问题描述】:
我有一个用例,我需要在 MongoDB 聚合中获取给定字段的值(仅在字符串中给出字段名称), 文档结构如下,
{
customer_id: '23424'
customer_23424_value: 5000
}
在 Mongo 聚合管道中,$getField 运算符非常适合获取字符串中给定字段名称的值,例如
{
$getField: {
field: 'customer_'+"$customer_id"+'_value' // 'customer_23424_value' can be written using concatenation
}
}
$getField 运算符从版本 5 开始引入 MongoDB,但我的生产机器在 4.4 中运行。 4.4 中是否有任何有效的 $getField 等价物或任何其他解决方法来做同样的事情
【问题讨论】:
-
你可以用 $objectToArray 和 $arrayToObject 操作符构造它
标签: mongodb mongodb-query aggregation-framework