使用 replaceOne()
可以替换整个文档,而使用 updateOne()
可以更新字段。
由于 replaceOne()
替换整个文档,因此不包含在新文档中的旧文档字段将会丢失。使用 updateOne()
可以添加新字段而不会失去旧文档中的字段。
例如,如果您有以下文档:
{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key3" : 3333
}
使用:
replaceOne({"_id" : ObjectId("0123456789abcdef01234567")}, { "my_test_key4" : 4})
导致结果:
{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key4" : 4.0
}
使用:
updateOne({"_id" : ObjectId("0123456789abcdef01234567")}, {$set: { "my_test_key4" : 4}})
导致结果为:
{
"_id" : ObjectId("0123456789abcdef01234567"),
"my_test_key3" : 3333.0,
"my_test_key4" : 4.0
}
请注意,在使用updateOne()
时,您可以在文档上使用更新运算符。
_id
始终更改为其他内容。 - caubupdateOne()
和replaceOne()
都不会更改_id
,而且两者都可以更改模式(文档的属性)。据我所知,当使用相同的筛选器和包含所有所需属性的更新/替换文档时,updateOne(<filter>, {$set: <document>}
和replaceOne(<filter>, <document>)
之间没有区别。 - Vince