📜  MongoDB – db.collection.findOneAndReplace() 方法(1)

📅  最后修改于: 2023-12-03 14:44:21.961000             🧑  作者: Mango

MongoDB – db.collection.findOneAndReplace() 方法

简介

db.collection.findOneAndReplace() 是 MongoDB 提供的一种用于替换文档的方法。它可以根据指定的查询条件查找到匹配的文档并进行替换操作。该方法只替换第一个匹配的文档,如果需要替换所有匹配的文档,可以使用 db.collection.updateMany() 方法。

用法
语法
db.collection.findOneAndReplace(
  <filter>,
  <replacement>,
  {
    projection: <projection>,
    sort: <sort>,
    maxTimeMS: <maxTimeMS>,
    upsert: <upsert>,
    returnNewDocument: <returnNewDocument>
  }
)
参数
  • <filter>: 一个文档,指定用于查找待替换的文档的查询条件。
  • <replacement>: 一个文档,指定替换后的新文档内容。
  • projection (可选): 一个文档,指定返回结果中包含的字段,默认为返回所有字段。
  • sort (可选): 一个文档,指定查询结果的排序规则。默认不排序。
  • maxTimeMS (可选): 操作超时时间,默认为不限制。
  • upsert (可选): 如果设置为 true,当找不到匹配的文档时,将会插入指定的替换文档。默认为 false。
  • returnNewDocument (可选): 如果设置为 true,替换后的文档将会作为结果返回。默认为 true。
返回值

该方法返回被替换的文档。

示例

考虑以下的users集合:

{ "_id": 1, "name": "Alice", "age": 30 }
{ "_id": 2, "name": "Bob", "age": 35 }
{ "_id": 3, "name": "Charlie", "age": 40 }

我们可以使用 findOneAndReplace() 方法替换匹配的文档:

db.users.findOneAndReplace(
   { "name": "Bob" },
   { "_id": 2, "name": "Robert", "age": 38 }
)

执行上述操作后,name 为 "Bob" 的文档将会被替换为 "_id": 2, "name": "Robert", "age": 38

注意事项
  • findOneAndReplace() 方法可以对集合执行原子替换操作,确保只有一个线程执行替换。