在我的应用程序中,我需要编辑文档...在编辑文档时,当前[未更改]版本应该仍可供其他用户使用。例如,当我开始编辑文档时,我在一个单独的集合中创建它的新副本,完成后我用新版本的临时集合替换当前版本。
我们假设存储在集合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
那说,更新整个文档的正确方法是什么?
答案 0 :(得分:4)
要替换整个文档,您不能使用$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" }
]
})