首页 > 解决方案 > 如何更新嵌套数组以向每个元素添加唯一的 ObjectId?

问题描述

我尝试了 2 种方法,但都没有奏效

db.exams.updateMany({},{$set: {"exams.$[].questions.$[].id" : new ObjectId()  }  })

db.exams.aggregate([
    {$unwind:"$exams"},
    {$unwind:"$exams.questions"},
    {$unwind:"$exams.questions.question"},
    {$set:{"exams.questions.id" : new ObjectId() }}
])

我不断为所有元素获得相同的 ObjectId,但我希望它为每个元素生成一个新的 objectId

标签: mongodb

解决方案


像这样的东西应该工作。我没有测试过...

db.exams.aggregate([
  {$map: {$input: "exams.questions.id", as: "id" in: new ObjectId()} },
  {$out: "your collection"}
  ])

推荐阅读