Database Manual / Reference / mongosh Methods / Collections

db.collection.deleteMany() (mongosh method方法)

Definition定义

db.collection.deleteMany()

Removes all documents that match the filter from a collection.从集合中删除与filter匹配的所有文档。

Returns:返回A document containing: 包含以下内容的文件:
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled如果操作在写入关注下运行,则布尔值acknowledgedtrue,如果写入关注被禁用,则acknowledgedfalse
  • deletedCount containing the number of deleted documentsdeletedCount包含已删除文档的数量

Note

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 shard the recreated collection.如果原始集合被分片,您还必须对重新创建的集合进行分片

For more information on dropping a collection, see db.collection.drop().有关删除集合的更多信息,请参阅db.collection.drop()

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The deleteMany() method has the following syntax:deleteMany()方法具有以下语法:

db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document>|<string>,
maxTimeMS: <int>,
let: <document>
}
)
Parameter参数Type类型Description描述
filterdocument文档

Specifies deletion criteria using query operators.使用查询运算符指定删除条件。

To delete all documents in a collection, pass in an empty document ({ }).若要删除集合中的所有文档,请传入一个空文档({ })。

writeConcerndocument文档

Optional. 可选。A document expressing the write concern. 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.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写关注

collationdocument文档

Optional.可选。

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: {
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. For descriptions of the fields, see Collation Document.指定排序规则时,locale字段是必填的;所有其他排序字段都是可选的。有关字段的描述,请参阅排序规则文档

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文档

Optional. 可选。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

maxTimeMSinteger整数

Optional. 可选。Specifies the time limit in milliseconds for the delete operation to run before timing out.指定删除操作在超时前运行的时间限制(以毫秒为单位)。

letDocument文档

Optional.可选。

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>. For example: $$targetTotal.要在命令中访问变量的值,请使用双美元符号前缀($$)和变量名,格式为$$<variable_name>。例如:$$targetTotal

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 Update with let Variables.有关使用let和变量的完整示例,请参阅使用let变量更新

Behavior行为

Sharded Collections分片化集合

  • If deleteMany() is run outside a transaction, operations that target more than one shard broadcast the operation to all shards in the cluster.如果deleteMany()在事务外部运行,则针对多个分片的操作会将该操作广播到集群中的所有分片。
  • If deleteMany() is run inside a transaction, operations that target more than one shard only target the relevant shards.如果deleteMany()在事务中运行,则针对多个分片的操作只针对相关分片。

Warning

Due to concurrent chunk migrations, deleteMany() might run without deleting all documents that match the specified filter. To ensure you delete all matching documents, perform one of the following operations:由于并发块迁移,deleteMany()可能会在不删除与指定筛选器匹配的所有文档的情况下运行。要确保删除所有匹配的文档,请执行以下操作之一:

  • Run the deleteMany() method iteratively until the corresponding find query with the same filter returns no documents.迭代运行deleteMany()方法,直到具有相同筛选器的相应查找查询不返回任何文档。
  • Run deleteMany() within a transaction.在事务中运行deleteMany()
  • Schedule the balancing window so chunk migrations only occur at specific times, and run any deleteMany() operations outside of the specified window.安排平衡窗口,使块迁移仅在特定时间发生,并在指定窗口外运行任何deleteMany()操作。

Delete a Single Document删除单个文档

To delete a single document, use db.collection.deleteOne() instead.要删除单个文档,请改用db.collection.deleteOne()

Alternatively, use a field that is a part of a unique index such as _id.或者,使用作为唯一索引(如_id)一部分的字段。

Transactions事务

db.collection.deleteMany() can be used inside distributed 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, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed 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 distributed transactions.也就是说,对于许多场景,适当地对数据进行建模将最大限度地减少对分布式事务的需求。

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

Primary Node Failure主节点故障

db.collection.deleteMany() deletes documents one at a time. If the primary node fails during a db.collection.deleteMany() operation, documents that were not yet deleted from secondary nodes are not deleted from the collection.一次删除一个文档。如果主节点在db.collection.deleteMany()操作期间发生故障,则尚未从辅助节点删除的文档不会从集合中删除。

Oplog Entries操作日志条目

If a db.collection.deleteMany() operation successfully deletes one or more documents, the operation adds an entry for each deleted document on the oplog (operations log). 如果db.collection.deleteMany()操作成功删除了一个或多个文档,则该操作会在oplog(操作日志)上为每个已删除的文档添加一个条目。If the operation fails or does not find any documents to delete, the operation does not add an entry on the oplog.如果操作失败或找不到任何要删除的文档,则操作不会在oplog上添加条目。

Examples示例

Delete Multiple Documents删除多个文档

The orders collection has documents with the following structure:orders集合具有以下结构的文档:

db.orders.insertOne(
{
_id: ObjectId("563237a41a4d68582c2509da"),
stock: "Brent Crude Futures",
qty: 250,
type: "buy-limit",
limit: 48.90,
creationts: ISODate("2015-11-01T12:30:15Z"),
expiryts: ISODate("2015-11-01T12:35:15Z"),
client: "Crude Traders Inc."
}
)

The following operation deletes all documents where client : "Crude Traders Inc.":以下操作删除客户为client : "Crude Traders Inc."(原油事务商股份有限公司)的所有文件:

try {
db.orders.deleteMany( { "client" : "Crude Traders Inc." } );
} catch (e) {
print (e);
}

The operation returns:操作返回:

{ "acknowledged" : true, "deletedCount" : 10 }

The following operation deletes all documents where stock : "Brent Crude Futures" and limit is greater than 48.88:以下操作删除所有stock : "Brent Crude Futures"(布伦特原油期货)且limit大于48.88的文档:

try {
db.orders.deleteMany( { "stock" : "Brent Crude Futures", "limit" : { $gt : 48.88 } } );
} catch (e) {
print (e);
}

The operation returns:操作返回:

{ "acknowledged" : true, "deletedCount" : 8 }

deleteMany() with a Timeout and Query Variables带超时和查询变量的deleteMany()

The following operation deletes all documents where client is equal to the targetClient variable and sets a time limit of 3 seconds:以下操作删除client等于targetClient变量的所有文档,并设置3秒的时间限制:

try {
db.orders.deleteMany(
{ $expr: { $eq: ["$client", "$$targetClient"] } },
{
let: { targetClient: "Crude Traders Inc." },
maxTimeMS: 3000
}
);
} catch (e) {
print(e);
}

The operation returns:操作返回:

{ "acknowledged" : true, "deletedCount" : 1 }

deleteMany() with Write ConcerndeleteMany()与写入关注

Given a three member replica set, the following operation specifies a w of majority and wtimeout of 100:给定一个由三个成员组成的副本集,以下操作指定wmajoritywtimeout100

try {
db.orders.deleteMany(
{ "client" : "Crude Traders Inc." },
{ writeConcern: { w : "majority", wtimeout : 100 }}
);
} catch (e) {
print (e);
}

If the acknowledgment takes longer than the wtimeout limit, the following exception is thrown:如果确认时间超过wtimeout限制,则抛出以下异常:

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

Specify Collation指定排序规则

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

A collection restaurants has the following documents:集合restaurants有以下文件:

db.restaurants.insertMany( [
{ _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.restaurants.deleteMany(
{ category: "cafe", status: "A" },
{ collation: { locale: "fr", strength: 1 } }
)

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

In mongosh, create a members collection with the following documents:mongosh中,使用以下文档创建一个成员集合:

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.members.deleteMany(
{ "points": { $lte: 20 }, "status": "P" },
{ hint: { status: 1 } }
)

Note

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

The delete command returns the following:delete命令返回以下内容:

{ "acknowledged" : true, "deletedCount" : 3 }

To view the indexes used, you can use the $indexStats pipeline:要查看使用的索引,可以使用$indexStats管道:

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

The accesses.ops field in the $indexStats output indicates the number of operations that used the index.$indexStats输出中的accesses.ops字段指示使用索引的操作数。