【问题标题】:$getField equivalent in mongodb aggregation pipelinemongodb 聚合管道中的 $getField 等效项
【发布时间】: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


【解决方案1】:

没有直接的方法来处理这种情况,仅供参考,请检查下面的查询,它的性能很昂贵,

  • $objectToArray 将根对象转换为键值格式的数组
  • $filter 迭代上述转换数组的循环
  • $concat 通过连接必填字段来创建键名
  • 上述过程将返回过滤后的属性
  • $let 创建一个变量来存储上述过滤结果并使用$first 返回第一个元素值
  • $eq检查条件上面的值等于5000
db.collection.find({
  $expr: {
    $eq: [
      {
        $let: {
          vars: {
            root: {
              $filter: {
                input: { $objectToArray: "$$ROOT" },
                cond: {
                  $eq: [
                    "$$this.k",
                    { $concat: ["customer_", "$customer_id", "_value"] }
                  ]
                }
              }
            }
          },
          in: { $first: "$$root.v" }
        }
      },
      5000
    ]
  }
})

Playground

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2015-04-24
    • 2020-09-20
    相关资源
    最近更新 更多