Definition定义
db.collection.deleteMany()Removes all documents that match the从集合中删除与filterfrom a collection.filter匹配的所有文档。Returns:返回A document containing:包含以下内容的文件:A boolean如果操作在写入关注下运行,则布尔值acknowledgedastrueif the operation ran with write concern orfalseif write concern was disabledacknowledged为true,如果写入关注被禁用,则acknowledged为falsedeletedCountcontaining 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>
}
)
filter |
| |
writeConcern |
| |
collation |
| |
hint |
| |
maxTimeMS |
| |
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:w为majority,wtimeout为100:
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
hint for Delete OperationsIn 在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字段指示使用索引的操作数。