MongoDB 批量操作有两种选择:
-
Adds a single document update operation to a bulk operations list. The operation can either replace an existing document or update specific fields in an existing document.
-
Adds a single document replacement operation to a bulk operations list. Use the
Bulk.find()
method to specify the condition that determines which document to replace. TheBulk.find.replaceOne()
method limits the replacement to a single document.
根据文档,这两种方法都可以替换匹配的文档。我是否理解正确, updateOne()
是更通用的方法,可以像 replaceOne()
一样替换文档,或者只是更新其特定字段?
最佳答案
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()
您可以在文档上使用 update operators。
关于mongodb - MongoDB 中的 replaceOne() 和 updateOne() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35848688/