node.js - 如何在 MongoDB 中动态设置我希望更新的字段

我需要更新高度嵌套数组对象的特定元素,但我无法动态选择字段有什么想法吗?我基本上需要在 for 循环中运行以下内容。

collection.updateOne({ _id: "MY_ID"},[
  {
    $set: {
       `array1.${i}.array2.${j}.id_field` : new UUID()
    },
  },
])

回答1

想通了,我所要做的就是将字符串括在方括号 [] 中。

collection.updateOne({ _id: "MY_ID"},[
  {
    $set: {
       [`array1.${i}.array2.${j}.id_field`] : new UUID()
    },
  },
])

相似文章

随机推荐

最新文章