“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

db.collection.replaceOne()

在此页面上

  • 定义
  • 兼容性
  • 语法
  • 行为
  • 举例
db.collection.replaceOne(filter, replacement, options)

重要

mongosh 方法

本页面提供 mongosh 方法的相关信息。这不是数据库命令或特定语言驱动程序(例如 Node.js)的相关文档。

有关数据库命令,请参阅 update命令。

如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。

对于传统 mongo Shell 文档,请参阅相应 MongoDB Server 版本的文档:

mongo shell v4.4

根据筛选器替换集合内的单个文档。

返回:文档包含以下内容:
  • 如果操作使用写关注来运行,则布尔值 acknowledgedtrue;如果已禁用写关注,则为 false

  • matchedCount 包含匹配文档的数量

  • modifiedCount 包含已修改文档的数量

  • upsertedId ,包含用于已更新或插入的文档的 _id

可以使用 db.collection.replaceOne() 查找托管在以下环境中的部署:

  • MongoDB Atlas :用于在云中部署 MongoDB 的完全托管服务

replaceOne() 方法采用以下形式:

db.collection.replaceOne(
<filter>,
<replacement>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
hint: <document|string>
}
)

replaceOne() 方法使用以下参数:

参数
类型
说明
筛选器
文档

更新的选择条件。可以使用与 find() 方法中相同的查询选择器

指定一个空文档 { } 以替换集合中返回的第一个文档。

replacement
文档

替换文档。

不能包含更新操作符

upsert
布尔

可选。当为 true 时,replaceOne() 将:

  • 如果没有与 filter 匹配的文档,则插入 replacement 参数所指定的文档。

  • 将与 filter 匹配的文档替换为 replacement 文档。

如果 filterreplacement 文档中均未指定 _id 字段,MongoDB 会将该字段添加到替换文档中。如果 _id 存在于这两者中,则两个值必须相等。

要避免多次更新或插入,请确保 query 字段具有唯一索引。

默认值为 false

writeConcern
文档

可选。表达写关注的文档。省略以使用默认写关注。

如果是在事务中运行,则请勿显式设置此操作的写关注。要将写关注与事务一起使用,请参阅事务和写关注。

collation
文档

可选。

指定用于操作的排序规则

排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号规则。

排序规则选项的语法如下:

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}

指定排序规则时,locale 字段为必填字段;所有其他排序规则字段均为可选字段。有关字段的说明,请参阅排序规则文档

如果未指定排序规则,但集合具有默认排序规则(请参阅 db.createCollection()),则操作将使用为集合指定的排序规则。

如果没有为收集或操作指定排序规则,MongoDB 将使用先前版本中使用的简单二进制比较来进行字符串比较。

您不能为一个操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果执行带排序的查找,则不能使用一种排序规则进行查找而另一种排序规则进行排序。

文档

可选。一个文档或字符串,它可以用指定用来支持过滤器索引

该选项可以采用索引规范文档或索引名称字符串。

如果指定不存在的索引,则操作出错。

有关示例,请参阅replaceOne 指定 hint

replaceOne() 使用 replacement 文档替换集合中与 filter 匹配的第一个匹配文档。

如果 upsert: true 且没有与 filter 匹配的文档,db.collection.replaceOne() 则会根据 replacement 文档创建一个新文档。

如果在一个分片集合上指定 upsert: true,则必须在 filter 中包含完整的分片键。有关分片集合的其他 db.collection.replaceOne() 行为,请参阅分片集合

请参阅用更新或插入替换

如果替换操作更改了文档大小,则操作将失败。

不能对时间序列集合使用 replaceOne() 方法。

db.collection.replaceOne() 首先尝试使用查询过滤器来定位单个分片。该操作如果无法通过查询过滤器定位单个分片,则会尝试通过替换文档定位。

在早期版本中,该操作会尝试使用替换文档定位。

替换文档不需要包含分片键。

警告

分片集合中的文档可能缺少分片键字段。采取预防措施,避免在更改文档的分片键值时意外删除分片键。

包含分片集合上 upsert: truedb.collection.replaceOne() 操作必须在 filter 中包含完整的分片键。

但是,分片集合中的文档可能缺少分片键字段。要定位缺失分片键的文档,可将 null 等值匹配 其他过滤条件(例如针对 _id 字段)结合使用。例如:

{ _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key

您可以更新文档的分片键值,除非分片键字段是不可变的 _id 字段。

警告

分片集合中的文档可能缺少分片键字段。采取预防措施,避免在更改文档的分片键值时意外删除分片键。

要修改现有的分片键值(使用db.collection.replaceOne()):

  • 必须mongos 上运行。请勿直接对分片发出此操作。

  • 必须事务中运行,或者以可重试写入的形式运行。

  • 必须对完整分片键包含等值过滤器

分片集合中的文档可能缺少分片键字段。要使用 db.collection.replaceOne() 来设置文档缺失的分片键,则必须mongos 上运行。请直接对分片发出此操作。

此外,以下要求也适用:

任务
要求
若要设为 null
  • 如果指定了 upsert: true,则需要对完整的分片键使用相等筛选器。

要设置为非 null
  • 必须事务中或作为可重试写入执行。

  • 如果满足以下任一条件,则需使用针对完整分片键的相等筛选器:

    • upsert: true,或

    • 新分片键值属于不同的分片。

提示

由于缺失的键值是作为 null 相等匹配的一部分返回的,因此为避免更新空值键,请酌情纳入其他查询条件(例如 _id 字段)。

另请参阅:

db.collection.replaceOne() 可以在分布式事务中使用。

重要

在大多数情况下,与单文档写入操作相比,分布式事务会产生更高的性能成本,并且分布式事务的可用性不应取代有效的模式设计。在许多情况下,非规范化数据模型(嵌入式文档和数组)仍然是数据和使用案例的最佳选择。换言之,对于许多场景,适当的数据建模将最大限度地减少对分布式事务的需求。

有关其他事务使用注意事项(如运行时间限制和 oplog 大小限制),另请参阅生产注意事项

如果分布式事务不是跨分片写入事务,则可以在该事务中创建集合和索引。

具有 upsert: truedb.collection.replaceOne() 可以在现有集合或不存在的集合上运行。如果在不存在的集合上运行,该操作将创建集合。

提示

如果是在事务中运行,则请勿显式设置此操作的写关注。要将写关注与事务一起使用,请参阅事务和写关注。

restaurant 集合包含以下文档:

{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan" },
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
{ "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }

如下操作将替换一个 name: "Central Perk Cafe" 的单个文档:

try {
db.restaurant.replaceOne(
{ "name" : "Central Perk Cafe" },
{ "name" : "Central Pork Cafe", "Borough" : "Manhattan" }
);
} catch (e){
print(e);
}

该操作返回:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

如果未找到匹配项,那么操作将返回:

{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }

如果未找到匹配项,设置 upsert: true 则会插入此文档。请参阅用 Upsert 进行替换

restaurant 集合包含以下文档:

{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
{ "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }

以下操作会尝试使用 upsert : true 来替换 name : "Pizza Rat's Pizzaria" 的文档:

try {
db.restaurant.replaceOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 },
{ upsert: true }
);
} catch (e){
print(e);
}

upsert : true 以来,该文档是根据 replacement 文档插入的。该操作返回:

{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : 4
}

该集合现在包含以下文档:

{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
{ "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 },
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 }

给定一个三成员副本集,以下操作指定 majorityw100wtimeout

try {
db.restaurant.replaceOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ "name" : "Pizza Rat's Pub", "Borough" : "Manhattan", "violations" : 3 },
{ w: "majority", wtimeout: 100 }
);
} catch (e) {
print(e);
}

如果确认花费的时间超过wtimeout限制,则会引发以下异常:

WriteConcernError({
"code" : 64,
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : {
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})

下表解释了 errInfo.writeConcern.provenance 的可能值:

来源
说明
clientSupplied
应用程序中指定了写关注。
customDefault
写入关注源自自定义的默认值。请参阅 setDefaultRWConcern
getLastErrorDefaults
写关注源自副本集的 settings.getLastErrorDefaults 字段。
implicitDefault
在没有所有其他写入关注规范的情况下,写入关注源自服务器。

排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号规则。

集合 myColl 包含以下文档:

{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }

以下操作包括排序规则选项:

db.myColl.replaceOne(
{ category: "cafe", status: "a" },
{ category: "cafÉ", status: "Replaced" },
{ collation: { locale: "fr", strength: 1 } }
);

使用以下文档创建示例 members 集合:

db.members.insertMany([
{ "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
{ "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null },
{ "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
])

在集合上创建以下索引:

db.members.createIndex( { status: 1 } )
db.members.createIndex( { points: 1 } )

以下更新操作明确提示使用索引 { status: 1 }

注意

如果指定不存在的索引,则操作出错。

db.members.replaceOne(
{ "points": { $lte: 20 }, "status": "P" },
{ "misc1": "using index on status", status: "P", member: "replacement", points: "20"},
{ hint: { status: 1 } }
)

该操作返回以下内容:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

要查看使用的索引,可以使用 $indexStats 管道:

db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )
← db.collection.renameCollection()