对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

db. 集合.replaceOne()(mongosh方法)

带驱动程序的 MongoDB

This page documents a mongosh method. To see the equivalent method in a MongoDB driver, see the corresponding page for your programming language:
db.collection.replaceOne(filter, replacement, options)

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

返回:

文档包含以下内容:

  • 如果操作使用写关注来运行,则布尔值 acknowledgedtrue;如果已禁用写关注,则为 false

  • matchedCount 包含匹配文档的数量

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

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

此方法可用于以下环境中托管的部署:

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

注意

所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令

The replaceOne() method has the following form:

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

The replaceOne() method takes the following parameters:

Parameter
类型
说明

文档

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

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

replacement

文档

替换文档。

不能包含更新操作符

upsert

布尔

Optional. When true, replaceOne() either:

  • 如果没有与 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 将使用先前版本中使用的简单二进制比较来进行字符串比较。

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

文档

Optional. A document or string that specifies the index to use to support the filter.

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

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

For an example, see Specify hint for replaceOne.

replaceOne() replaces the first matching document in the collection that matches the filter, using the replacement document.

If upsert: true and no documents match the filter, db.collection.replaceOne() creates a new document based on the replacement document.

If you specify upsert: true on a sharded collection, you must include the full shard key in the filter. For additional db.collection.replaceOne() behavior on a sharded collection, see Sharded Collections.

请参阅用更新或插入替换

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

You cannot use the replaceOne() method on a time series collection.

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

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

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

警告

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

A db.collection.replaceOne() operation that includes upsert: true on a sharded collection must include the full shard key in the filter.

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

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

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

警告

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

To modify the existing shard key value with db.collection.replaceOne():

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

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

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

Documents in a sharded collection can be missing the shard key fields. To use db.collection.replaceOne() to set the document's missing shard key, you must run on a mongos. Do not issue the operation directly on the shard.

此外,以下要求也适用:

任务
要求

若要设为 null

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

要设置为非 null

  • 必须事务中或作为可重试写入执行。

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

    • upsert: true,或

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

提示

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

另请参阅:

db.collection.replaceOne() can be used inside distributed transactions.

重要

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

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

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

db.collection.replaceOne() with upsert: true can be run on an existing collection or a non-existing collection. If run on a non-existing collection, the operation creates the collection.

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

restaurant 集合包含以下文档:

db.restaurant.insertMany ( [
{ _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 则会插入该文档。请参阅利用更新或插入替换

restaurant 集合包含以下文档:

db.restaurant.insertMany( [
{ _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 包含以下文档:

db.myColl.insertMany( [
{ _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 } } ] )
给本页内容打分