【问题标题】:Update all array subobjects relative to their own current value相对于它们自己的当前值更新所有数组子对象
【发布时间】:2023-01-16 00:26:47
【问题描述】:

假设我想将所有嵌套值乘以 10。

{
  foos: [
    { val: 1 },
    { val: 10 },
    { val: 5 },
  ]
}
// to
{
  foos: [
    { val: 10 },
    { val: 100 },
    { val: 50 },
  ]
}

由于我们重用了现有的字段值,我假设我将不得不使用聚合运算符。

这里有一些尝试:

// Does not work, since it it unwinds the values from their parent object.
coll.updateMany({}, [
  {$set: {
    foos: {$map: {
      input: '$foos',
      as: 'foo',
      in: {$multiply: ['$$foo.val', 10]}
    }}
  }}
])
// MongoServerError: $multiply only supports numeric types, not string
coll.updateMany({}, [
  {
    $set: {
      'foos.val': {$multiply: ['$foos.$.val', 10]}
    }
  }
])

如果不获取文档并使用 JS 循环继续更新,这是否可能?

就像是:

coll.updateMany({}, [
  {
    $set: {
      foos: {
        $map: {
          input: '$foos',
          as: 'foo',
          in: {
            $project: {
              blackMagicToSpreadtheOriginalFoo: '$$foo', // FIXME
              val: { $multiply: ['$$foo.val', 10] }
            }
          }
        }
      }
    }
  }
])

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    在这种情况下,为什么需要:blackMagicToSpreadtheOriginalFoo: '$$foo', // FIXME?为什么不简单地:

    coll.updateMany({},
    [
      {
        $set: {
          foos: {
            $map: {
              input: "$foos",
              in: {val: {$multiply: ["$$this.val", 10]}}
            }
          }
        }
      }
    ])
    

    查看它在playground example 上的工作原理

    如果蚀刻项目中有其他键,只需使用$mergeObjects

    coll.updateMany({},
    [
      {
        $set: {
          foos: {
            $map: {
              input: "$foos",
              in: {
                $mergeObjects: [
                  "$$this",
                  {val: {$multiply: ["$$this.val", 10]}}
                ]
              }
            }
          }
        }
      }
    ])
    

    查看它在playground example - with keys 上的工作原理

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2011-08-17
      • 2017-12-13
      相关资源
      最近更新 更多