Docs HomeMongoDB Manual

delete

Definition定义

delete

The delete command removes documents from a collection. delete命令从集合中删除文档。A single delete command can contain multiple delete specifications. The delete methods provided by the MongoDB drivers use this command internally.单个delete命令可以包含多个删除规范。MongoDB驱动程序提供的删除方法在内部使用此命令。

Changed in version 5.0.5.0版更改。

Tip

In mongosh, this command can also be run through the deleteOne(), deleteMany(), and findOneAndDelete() helper methods.mongosh中,该命令也可以通过deleteOne()deleteMany()findOneAndDelete()辅助方法运行。

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. 助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。In cases where the convenience is not needed or the additional return fields are required, use the database command.如果不需要方便,或者需要额外的返回字段,请使用数据库命令。

Returns:返回值:A document that contains the status of the operation. 包含操作状态的文档。See Output for details.有关详细信息,请参阅输出

Syntax语法

The command has the following syntax:该命令具有以下语法:

 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>
}
)

Command Fields命令字段

The command takes the following fields:该命令包含以下字段:

Field字段Type类型Description描述
deletestringThe name of the target collection. 目标集合的名称。
deletesarrayAn array of one or more delete statements to perform in the named collection. 要在命名集合中执行的一个或多个delete语句的数组。
commentanyOptional.可选的。
A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations: 要附加到此命令的用户提供的注释。设置后,此注释将与此命令的记录一起显示在以下位置: A comment can be any valid BSON type (string, integer, object, array, etc). 注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。
New in version 4.4. 4.4版新增。
letdocumentOptional.可选的。
Specifies a document with a list of variables. 指定具有变量列表的文档。This allows you to improve command readability by separating the variables from the query text.这允许您通过将变量与查询文本分离来提高命令的可读性。
The document syntax is: 文档语法为:
{ <variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n> }
The variable is set to the value returned by the expression, and cannot be changed afterwards.变量设置为表达式返回的值,之后不能更改。
To access the value of a variable in the command, use the double dollar sign prefix ($$) together with your variable name in the form $$<variable_name>. 要访问命令中变量的值,请使用双美元符号前缀($$)和形式为$$<variable_name>的变量名。For example: $$targetTotal.
Note
To use a variable to filter results, you must access the variable within the $expr operator. 若要使用变量筛选结果,必须访问$expr运算符中的变量。
For a complete example using let and variables, see Use Variables in let. 有关使用let和变量的完整示例,请参阅let中使用变量
New in version 5.0. 5.0版新增。
orderedbooleanOptional.可选的。If true, then when a delete statement fails, return without performing the remaining delete statements. 如果为true,则当delete语句失败时,返回而不执行其余的delete语句。If false, then when a delete statement fails, continue with the remaining delete statements, if any. Defaults to true. 如果为false,则当delete语句失败时,继续使用剩余的delete语句(如果有的话)。默认为true
writeConcerndocumentOptional.可选的。A document expressing the write concern of the delete command. 表示删除命令的写入关注的文档。Omit to use the default write concern.忽略使用默认的写入关注。
Do not explicitly set the write concern for the operation if run in a transaction. 如果在事务中运行,请不要显式设置操作的写入关注。To use write concern with transactions, see Transactions and Write Concern. 要在事务中使用写入关注,请参阅事务和写入关注
maxTimeMSnon-negative integerOptional.可选的。
Specifies a time limit in milliseconds. If you do not specify a value for maxTimeMS, operations will not time out. A value of 0 explicitly specifies the default unbounded behavior.指定以毫秒为单位的时间限制。如果不指定maxTimeMS的值,操作将不会超时。值0显式指定默认的无边界行为。
MongoDB terminates operations that exceed their allotted time limit using the same mechanism as db.killOp(). MongoDB使用与db.killOp()相同的机制终止超过指定时间限制的操作。MongoDB only terminates an operation at one of its designated interrupt points. MongoDB只在其指定的中断点之一终止操作。

Each element of the deletes array contains the following fields:deletes数组的每个元素都包含以下字段:

Field字段Type类型Description描述
qdocumentThe query that matches documents to delete. 与要删除的文档匹配的查询。
limitintegerThe number of matching documents to delete. 要删除的匹配文档数。Specify either a 0 to delete all matching documents or 1 to delete a single document. 指定0以删除所有匹配的文档,或指定1以删除单个文档。
collationdocumentOptional.可选的。
Specifies the collation to use for the operation.指定要用于操作的排序规则
collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音标记的规则。
The collation option has the following syntax: collation选项具有以下语法:
collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
When specifying collation, the locale field is mandatory; all other collation fields are optional. 指定排序规则时,locale字段是必需的;所有其他排序规则字段都是可选的。For descriptions of the fields, see Collation Document.有关字段的说明,请参阅排序规则文档
If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.如果未指定排序规则,但集合具有默认排序规则(请参见db.createCollection()),则操作将使用为集合指定的排序规则。
If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.如果没有为集合或操作指定排序规则,MongoDB将使用以前版本中使用的简单二进制比较进行字符串比较。
You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort. 不能为一个操作指定多个排序规则。例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能为查找使用一个排序规则,为排序使用另一个排序顺序。
hintDocument or stringOptional.可选的。A document or string that specifies the index to use to support the query predicate.指定用于支持查询谓词索引的文档或字符串。
The option can take an index specification document or the index name string.该选项可以采用索引规范文档或索引名称字符串。
If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。
For an example, see Specify hint for Delete Operations. 有关示例,请参阅为删除操作指定hint
New in version 4.4. 4.4版新增。

Behavior行为

Sharded Collections分片集合

All delete operations for a sharded collection that specify the limit: 1 option must include the shard key or the _id field in the query specification.指定limit:1选项的分片集合的所有delete操作都必须包括查询规范中的分片键_id字段。

delete operations specifying limit: 1 in a sharded collection which do not contain either the shard key or the _id field return an error.在不包含分片键_id字段的分片集合中,指定limit:1delete操作返回错误。

Limits限制

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.deletes数组中所有查询的总大小(即q字段值)必须小于或等于BSON文档的最大大小

The total number of delete documents in the deletes array must be less than or equal to the maximum bulk size.deletes数组中的删除文档总数必须小于或等于最大批量大小

Transactions事务

delete can be used inside multi-document transactions.删除可以在多文档事务中使用。

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.如果在事务中运行,请不要显式设置操作的写入关注。要在事务中使用写入关注,请参阅事务和写入关注

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会产生更高的性能成本,并且多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入文档和数组)将继续是您的数据和用例的最佳选择。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,对数据进行适当建模将最大限度地减少对多文档事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项

Examples实例

Limit the Number of Documents Deleted限制删除的文档数量

The following example deletes from the orders collection one document that has the status equal to D by specifying the limit of 1:以下示例通过指定limit1,从orders集合中删除一个status等于D的文档:

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

The returned document shows that the command deleted 1 document. 返回的文档显示该命令删除了1个文档。See Output for details.有关详细信息,请参阅输出

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

All delete operations for a sharded collection that specify the limit: 1 option must include the shard key or the _id field in the query specification.指定limit:1选项的分片集合的所有delete操作都必须包括查询规范中的分片键_id字段。

delete operations specifying limit: 1 in a sharded collection which do not contain either the shard key or the _id field return an error.在不包含分片键_id字段的分片集合中,指定limit:1delete操作返回错误。

Delete All Documents That Match a Condition删除符合条件的所有文档

The following example deletes from the orders collection all documents that have the status equal to D by specifying the limit of 0:以下示例通过指定limit:0orders集合中删除status等于D的所有文档:

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 Output for details.返回的文档显示,该命令找到并删除了13个文档。有关详细信息,请参阅输出

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

Delete All Documents from a Collection从集合中删除所有文档

Delete all documents in the orders collection by specifying an empty query condition and a limit of 0:通过指定空查询条件0limit来删除orders集合中的所有文档:

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. 返回的文档显示,该命令总共发现并删除了35个文档。See Output for details.有关详细信息,请参阅输出

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

Bulk Delete批量删除

The following example performs multiple delete operations on the orders collection:以下示例对orders集合执行多个删除操作:

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 Output for details.返回的文档显示,该命令为两个delete语句总共找到并删除了21个文档。有关详细信息,请参阅输出

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

Specify Collation指定排序规则

collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音标记的规则。

A collection myColl has the following documents:集合myColl包含以下文档:

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

The following operation includes the collation option:以下操作包括排序规则选项

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

Specify hint for Delete Operations指定删除操作的hint

New in version 4.4. 4.4版新增。

In mongosh, create a members collection with the following documents: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" }
])

Create the following indexes on the collection:在集合上创建以下索引:

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

The following delete operation explicitly hints to use the index { status: 1 }:以下删除操作明确提示使用索引{ status: 1 }

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

If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作将出错。

To see the index used, run explain on the operation:要查看使用的索引,请对操作运行explain

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

Use Variables in letlet中使用变量

New in version 5.0. 5.0版新增。

To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let选项。

Note

To filter results using a variable, you must access the variable within the $expr operator.若要使用变量筛选结果,必须访问$expr运算符中的变量。

Create a collection cakeFlavors:创建一个集合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:以下示例在let中定义了targetFlavor变量,并使用该变量删除草莓蛋糕风味:

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

Output输出

The returned document contains a subset of the following fields:返回的文档包含以下字段的子集:

delete.ok

The status of the command.命令的状态。

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.writeErrors数组包含每个出错的delete语句的错误文档。

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.一个整数,用于标识deletes数组中的delete语句,该数组使用从零开始的索引。

delete.writeErrors.code

An integer value identifying the error.标识错误的整数值。

delete.writeErrors.errmsg

A description of the error.错误的描述。

delete.writeConcernError

Document that describe error related to write concern and contains the fields:描述与写入关注相关的错误并包含以下字段的文档:

delete.writeConcernError.code

An integer value identifying the cause of the write concern error.一个整数值,用于标识写入关注错误的原因。

delete.writeConcernError.errmsg

A description of the cause of the write concern error.写入关注错误原因的描述。

delete.writeConcernError.errInfo.writeConcern

New in version 4.4. 4.4版新增。

The write concern object used for the corresponding operation. 用于相应操作的写入关注对象。For information on write concern object fields, see Write Concern Specification.有关写入关注对象字段的信息,请参阅写入关注规范

The write concern object may also contain the following field, indicating the source of the write concern:写入关注对象还可能包含以下字段,指示写入关注的来源:

delete.writeConcernError.errInfo.writeConcern.provenance

A string value indicating where the write concern originated (known as write concern provenance). 一个字符串值,指示写入关注的来源(称为写入关注provenance)。The following table shows the possible values for this field and their significance:下表显示了该字段的可能值及其重要性:

Provenance来源Description描述
clientSuppliedThe write concern was specified in the application.写入关注已在应用程序中指定。
customDefaultThe write concern originated from a custom defined default value. 写入关注源自自定义定义的默认值。See setDefaultRWConcern.请参阅setDefaultRWConcern
getLastErrorDefaultsThe write concern originated from the replica set's settings.getLastErrorDefaults field.写入关注源自复制副本集的settings.getLastErrorDefaults字段。
implicitDefaultThe write concern originated from the server in absence of all other write concern specifications.在没有所有其他写入关注规范的情况下,写入关注源自服务器。

The following is an example document returned for a successful delete command:以下是成功delete命令返回的示例文档:

{ 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:以下是为delete命令返回的示例文档,该命令由于在hint字段中指定了不存在的索引而遇到错误:

{
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
}