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

标签 mongodb

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

假设存储在集合 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" }
  ]
}

如何替换 whoe 文件?问题是当我尝试用

更新原始文档时
{ "$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

也就是说,更新整个文档的正确方法是什么?

最佳答案

要替换整个文档,您不需要使用 $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" }
  ]
})

关于MongoDB:如何更新集合中的整个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24714022/

相关文章:

C# MongoDb 驱动程序包含子对象

python - 优化将一个 MongoDB 中的字段与另一个 MongoDB 进行比较时的速度

Node.js Mongoose 因复杂查询而变得困惑

mongodb - Robo 3T Sasl失败

arrays - 为动态填充的对象数组生成 Mongoose 模式

node.js - Docker:使用图像,跳过(docker-compose)

java - MongoDB 和 Spring MVC : PATCH operation?

mongodb - 如何将 mongodb 客户端连接到本地 Meteor MongoDB

java - mongo-java-driver 字段的最大值

node.js - 查询 MongoDB(通过 MongooseJS)并将结果保存在 Javascript 变量中?