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

标签 mongodb mongodb-query crud

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

关于mongodb - MongoDB 中的 replaceOne() 和 updateOne() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35848688/

相关文章:

mongodb - 嵌入式文档中两个值之间的差异

mongodb - 更新 MongoDB 中数组内数组内的嵌入对象

jquery - Rails 3.1 远程请求提交两次

php - 如何从 MongoDB 对象中提取时间戳

javascript - 使用 Javascript 从 MongoDB 返回中提取值。

c++ - 辅助节点上的 MongoDB 聚合框架

MongoDB ATLAS 到本地的迁移

mongodb - 如何在第一级数组上使用 $elemMatch?

javascript - 如何使我的 CRUD 应用程序离线工作?

asp.net - 使用 Web API 和数据库优先策略构建 ASP.Net 应用程序