updateMany中,只有field存在才更新field,不新建key

In updateMany, update the field only if field exists, and do not create a new key

所以我想在 $set 中做的是检查该字段是否存在然后更新值,但前提是该字段存在。 $cond 非常接近我想要实现的目标,但问题是我无法阻止它创建字段。

我可以过滤以仅获取现有字段,但在这种情况下,我将不得不逐个字段更新,而不是同时更新所有字段,这将花费很长时间。

 const data = await connection.collection("snapshot").updateMany({}, [
    {
      $set: {
        field1: {
          $cond: [
            { field1: { $exists: true } },
            { field1: "newValue" },
            undefined, // do nothing
          ],
        },
        field2: {
          $cond: [
            { field2: { $exists: true } },
            { field2: "newValue" },
            undefined, // do nothing
          ],
        },
        field3: {
          $cond: [
            { field3: { $exists: true } },
            { field3: "newValue" },
            undefined, // do nothing
          ],
        },
      },
    },
  ]);

我是不是遗漏了什么或者根本不可能做到?

我正在使用 mongo 5.0

运算符 $exists 仅适用于 find,不适用于聚合管道。检查“字段存在”并非易事,请参阅

我假设你喜欢像 { field3: "newValue" } 一样更新文档,你的更新会 { field3: { field3: "newValue" } }

总的来说就是这个:

connection.collection("snapshot").updateMany({}, [
   {
      $set: {
         field1: {
            $cond: [
               { $ne: [{ $type: "$field1" }, "missing"] },
               "newValue",
               "$$REMOVE" // do nothing
            ]
         },
         field2: {
            $cond: [
               { $ne: [{ $type: "$field2" }, "missing"] },
               "newValue",
               "$$REMOVE" // do nothing
            ]
         },
         field3: {
            $cond: [
               { $ne: [{ $type: "$field3" }, "missing"] },
               "newValue",
               "$$REMOVE" // do nothing
            ]
         }
      }
   }
])