Docs 菜单

删除

delete

The delete command removes documents from a collection. A single delete command can contain multiple delete specifications. The delete methods provided by the MongoDB drivers use this command internally.

5.0 版本中的更改

提示

In mongosh, this command can also be run through the deleteOne(), deleteMany(), and findOneAndDelete() helper methods.

辅助方法对 mongosh 用户来说很方便,但它们返回的信息级别可能与数据库命令不同。如果不追求方便或需要额外的返回字段,请使用数据库命令。

返回:包含操作状态的文档。有关详细信息,请参阅输出

此命令可用于以下环境中托管的部署:

注意

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

该命令具有以下语法:

db.runCommand(
{
delete: <collection>,
deletes: [
{
q : <query>,
limit : <integer>,
collation: <document>,
hint: <document|string>
},
...
],
comment: <any>,
let: <document>, // Added in MongoDB 5.0
ordered: <boolean>,
writeConcern: { <write concern> },
maxTimeMS: <integer>
}
)

该命令接受以下字段:

字段
类型
说明

字符串

目标集合的名称。

阵列

An array of one or more delete statements to perform in the named collection.

comment

any

可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:

注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。

文档

可选。

指定包含变量列表的文档。这样可以将变量与查询文本分开,从而提高命令的可读性。

文档语法为:

{
<variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n>
}

变量设置为表达式返回的值,并且之后不能再进行更改。

要访问命令中的变量值,请使用双美元符号前缀 ($) 以及 $<variable_name> 形式的变量名称。例如:$targetTotal

要使用变量筛选结果,您必须在 $expr 操作符中访问该变量。

For a complete example using let and variables, see Use Variables in let.

版本 5.0 中的新增功能

布尔

Optional. If true, then when a delete statement fails, return without performing the remaining delete statements. If false, then when a delete statement fails, continue with the remaining delete statements, if any. Defaults to true.

文档

可选。 表达 命令 写关注(write concern) delete的文档。省略以使用默认的写关注(write concern)。

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

maxTimeMS

non-negative integer

可选。

指定时间限制(以毫秒为单位)。如果您未指定 maxTimeMS 值,操作将不会超时。如果值为 0 ,则显式指定默认无限制行为。

MongoDB 使用与 db.killOp() 相同的机制终止超过分配的时间限制的操作。MongoDB 仅在指定的中断点之一中终止操作。

Each element of the deletes array contains the following fields:

字段
类型
说明

文档

The query that matches documents to delete.

整型

The number of matching documents to delete. Specify either a 0 to delete all matching documents or 1 to delete a single document.

文档

可选。

指定用于操作的排序规则

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

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

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

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

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

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

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

文档或字符串

可选。 指定用于支持查询谓词的索引的文档或字符串。

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

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

有关示例,请参阅为删除操作指定 hint

To use delete operations for a sharded collection that specify the limit: 1 option:

  • 如果您仅针对一个分片,则可以在查询规范中使用部分分片键,或者

  • 您可以在查询规范中提供分片键_id 字段。

The total size of all the queries (i.e. the q field values) in the deletes array must be less than or equal to the maximum BSON document size.

The total number of delete documents in the deletes array must be less than or equal to the maximum bulk size.

删除 can be used inside distributed transactions.

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

重要

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

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

The following example deletes from the orders collection one document that has the status equal to D by specifying the limit of 1:

db.runCommand(
{
delete: "orders",
deletes: [ { q: { status: "D" }, limit: 1 } ]
}
)

The returned document shows that the command deleted 1 document. See 输出 for details.

{ "ok" : 1, "n" : 1 }

注意

To use delete operations for a sharded collection that specify the limit: 1 option:

  • 如果您仅针对一个分片,则可以在查询规范中使用部分分片键,或者

  • 您可以在查询规范中提供分片键_id 字段。

The following example deletes from the orders collection all documents that have the status equal to D by specifying the limit of 0:

db.runCommand(
{
delete: "orders",
deletes: [ { q: { status: "D" }, limit: 0 } ],
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

The returned document shows that the command found and deleted 13 documents. See 输出 for details.

{ "ok" : 1, "n" : 13 }

注意

If you are deleting all documents in a large collection, it may be faster to drop the collection and recreate it. Before dropping the collection, note all indexes on the collection. You must recreate any indexes that existed in the original collection. If the original collection was sharded, you must also 分片 the recreated collection.

For more information on dropping a collection, see db.collection.drop().

Delete all documents in the orders collection by specifying an empty query condition and a limit of 0:

db.runCommand(
{
delete: "orders",
deletes: [ { q: { }, limit: 0 } ],
writeConcern: { w: "majority", wtimeout: 5000 }
}
)

The returned document shows that the command found and deleted 35 documents in total. See 输出 for details.

{ "ok" : 1, "n" : 35 }

The following example performs multiple delete operations on the orders collection:

db.runCommand(
{
delete: "orders",
deletes: [
{ q: { status: "D" }, limit: 0 },
{ q: { cust_num: 99999, item: "abc123", status: "A" }, limit: 1 }
],
ordered: false,
writeConcern: { w: 1 }
}
)

The returned document shows that the command found and deleted 21 documents in total for the two delete statements. See 输出 for details.

{ "ok" : 1, "n" : 21 }

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

集合 myColl 包含以下文档:

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

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

db.runCommand({
delete: "myColl",
deletes: [
{ q: { category: "cafe", status: "a" }, limit: 0, collation: { locale: "fr", strength: 1 } }
]
})

mongosh 中,创建一个 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.runCommand({
delete: "members",
deletes: [
{ q: { "points": { $lte: 20 }, "status": "P" }, limit: 0, hint: { status: 1 } }
]
})

注意

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

要查看使用的索引,请对操作运行 explain

db.runCommand(
{
explain: {
delete: "members",
deletes: [
{ q: { "points": { $lte: 20 }, "status": "P" }, limit: 0, hint: { status: 1 } }
]
},
verbosity: "queryPlanner"
}
)

版本 5.0 中的新增功能

要定义可在命令中其他位置访问的变量,请使用 let 选项。

注意

要使用变量筛选结果,您必须在 $expr 操作符中访问该变量。

创建集合 cakeFlavors

db.cakeFlavors.insertMany( [
{ _id: 1, flavor: "chocolate" },
{ _id: 2, flavor: "strawberry" },
{ _id: 3, flavor: "cherry" }
] )

The following example defines a targetFlavor variable in let and uses the variable to delete the strawberry cake flavor:

db.runCommand( {
delete: db.cakeFlavors.getName(),
deletes: [ {
q: { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
limit: 1
} ],
let : { targetFlavor: "strawberry" }
} )

返回的文档包含以下字段的子集:

delete.ok

命令的状态。

delete.n

The number of documents deleted.

delete.writeErrors

An array of documents that contains information regarding any error encountered during the delete operation. The writeErrors array contains an error document for each delete statement that errors.

Each error document contains the following information:

delete.writeErrors.index

An integer that identifies the delete statement in the deletes array, which uses a zero-based index.

delete.writeErrors.code

标识错误的整数值。

delete.writeErrors.errmsg

错误描述。

delete.writeConcernError

描述与写关注(write concern)相关的错误的文档。

在版本7.0.6 中进行了更改:(也适用于 6.0.14和5.0.30 ):当deletemongos 上执行时,即使发生一个或多个写入错误,也始终会报告写关注(write concern)错误。在以前的版本中,发生写入错误可能会导致 不报告写关注(writedelete concern)错误。

The writeConcernError documents contian the following fields:

delete.writeConcernError.code

一个整数值,用于标识写关注错误原因。

delete.writeConcernError.errmsg

写关注错误原因的描述。

delete.writeConcernError.errInfo.writeConcern

用于相应操作的写关注对象。有关写关注对象字段的信息,请参阅写关注规范

写关注对象还可能包含以下字段,指示写关注的来源:

delete.writeConcernError.errInfo.writeConcern.provenance

一个表示写关注来源(称为写关注provenance)的字符串值。下表显示该字段的可能值及其有效位数:

来源
说明

clientSupplied

应用程序中指定了写关注。

customDefault

写入关注源自自定义的默认值。请参阅 setDefaultRWConcern

getLastErrorDefaults

写关注源自副本集的 settings.getLastErrorDefaults 字段。

implicitDefault

在没有所有其他写入关注规范的情况下,写入关注源自服务器。

The following is an example document returned for a successful delete command:

{ ok: 1, n: 1 }

The following is an example document returned for a delete command that encountered an error because it specified a non-existent index in the hint field:

{
n: 0,
writeErrors: [
{
index: 0,
code: 2,
errmsg: 'error processing query: ns=test.products: hat $eq "bowler"\n' +
'Sort: {}\n' +
'Proj: {}\n' +
' planner returned error :: caused by :: hint provided does not correspond to an existing index'
}
],
ok: 1
}