MongoDB 中的 replaceOne() 和 updateOne() 有什么区别?

What's the difference between replaceOne() and updateOne() in MongoDB?

MongoDB批量操作有两种选择:

  1. Bulk.find.updateOne()

    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.

  2. Bulk.find.replaceOne()

    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. The Bulk.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

replaceOne() 替换整个文档,而 updateOne() 允许更新或添加字段。使用 updateOne() 时,您还可以访问 update operators,它可以可靠地对文档执行更新。例如,两个客户端可以 "simultaneously" 在同一文档中的同一字段上递增一个值,并且两个增量都将被捕获,而使用替换一个可能会覆盖另一个可能会丢失一个增量。

由于 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
}

db.collection.replaceOne()db.collection.updateOne().

做的完全一样

主要区别在于 db.collection.replaceOne() 正在编辑的数据必须来回发送到服务器,而 db.collection.UpdateOne() 将只请求过滤后的数据,而不是整个文档!