MongoDB:如何在集合中更新整个文档

12

在我的应用程序中,我需要编辑一个文档...并且在编辑文档时,当前的 [未更改] 版本仍应该对其他用户可用。例如,当我开始编辑文档时,我在一个单独的集合中创建了它的一个新副本,完成后,将临时集合的新版本替换为当前版本。

假设存储在集合users中的原始文档如下所示:

{
  "_id" : ObjectId("53b986e2fe000000019a5a13"),
  "name" : "Joe",
  "birthDate" : "2080-12-11",
  "publications" : [
    { "title" : "title 1", "description" : "description 1" },
    { "title" : "title 2", "description" : "description 2" }
  ]
}

那么,假设上面的文档被复制到另一个集合(例如users.wip)并进行了以下修改:

{
  "_id" : ObjectId("53b986e2fe000000019a5a13"),
  "name" : "Joe",
  "birthDate" : "1980-12-11",
  "publications" : [
    { "title" : "bye bye", "description" : "Blah blah" },
    { "title" : "title 2", "description" : "description 2" },
    { "title" : "title 3", "description" : "description 3" }
  ]
}

我该如何替换整个文档?问题在于,当我尝试使用

{ "$set" : {
  "name" : "Joe",
  "birthDate" : "1980-12-11",
  "publications" : [
    { "title" : "bye bye", "description" : "Blah blah" },
    { "title" : "title 2", "description" : "description 2" },
    { "title" : "title 3", "description" : "description 3" }
  ]
}}

我总是收到以下错误信息:

10150  Field name duplication not allowed with modifiers

话虽如此,更新整个文档的正确方式是什么?

1个回答

23

如果要替换整个文档,则不需要使用$set,只需将新文档提供给update调用即可:

db.test.update({"_id": ObjectId("53b986e2fe000000019a5a13")}, {
  "_id" : ObjectId("53b986e2fe000000019a5a13"),
  "name" : "Joe",
  "birthDate" : "1980-12-11",
  "publications" : [
    { "title" : "bye bye", "description" : "Blah blah" },
    { "title" : "title 2", "description" : "description 2" },
    { "title" : "title 3", "description" : "description 3" }
  ]
})

然而,使用当前的3.0驱动程序时,最好使用replaceOne代替:

db.test.replaceOne({"_id": ObjectId("53b986e2fe000000019a5a13")}, {
  "name" : "Joe",
  "birthDate" : "1980-12-11",
  "publications" : [
    { "title" : "bye bye", "description" : "Blah blah" },
    { "title" : "title 2", "description" : "description 2" },
    { "title" : "title 3", "description" : "description 3" }
  ]
})

替换后,它的ID会改变吗? - Amir Fo
2
除非您在替换文档中提供一个新的 _id 值,否则 _id 值将保持不变。 - JohnnyHK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接