db.collection.deleteMany()
On this page本页内容
Definition定义
db.collection.deleteMany()
- Important
mongosh Method
This page documents a
mongosh
method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see the
delete
command.For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:Removes all documents that match the从集合中删除所有与filter
from a collection.filter
匹配的文档。db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)Parameter参数Type类型Description描述filter
document Specifies deletion criteria using query operators.使用查询运算符指定删除条件。
To delete all documents in a collection, pass in an empty document (若要删除集合中的所有文档,请传入一个空文档({ }
).{ }
)。writeConcern
document 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.要在事务中使用写入关注,请参阅事务和写入关注。collation
document Optional.可选的。
Specifies the collation to use for the operation.指定要用于操作的collation
。
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.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能为查找使用一个排序规则,为排序使用另一个排序顺序。hint
document 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
。
New in version 4.4.4.4版新增。Returns:返回值:A document containing:包含以下内容的文档:-
A boolean如果操作在有写入关注的情况下运行,则布尔值acknowledged
astrue
if the operation ran with write concern orfalse
if write concern was disabledacknowledged
为true
;如果写入关注被禁用,则acknowledged
为false
deletedCount
containing the number of deleted documents包含已删除文档的数量
-
Behavior行为
Time Series Collections时间序列集合
如果在时间序列集合上使用db.collection.deleteMany()
throws a WriteError
exception if used on a time series collection. db.collection.deleteMany()
,则会引发WriteError
异常。To remove all documents from a time series collection, use 要从时间序列集合中删除所有文档,请使用db.collection.drop()
.db.collection.drop()
。
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 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.要在事务中使用写入关注,请参阅事务和写入关注。
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.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项。
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()
操作期间失败,则尚未从辅助节点删除的文档不会从集合中删除。
Examples实例
Delete Multiple Documents删除多个文档
The orders
collection has documents with the following structure:orders
集合包含具有以下结构的文档:
{
_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 Write Concern带写入关注的deleteMany()
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." },
{ w : "majority", wtimeout : 100 }
);
} catch (e) {
print (e);
}
If the acknowledgement 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" : { // Added in MongoDB 4.4
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})
See also: 另请参阅:
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:以下操作包括collation
选项:
db.myColl.deleteMany(
{ category: "cafe", status: "A" },
{ collation: { locale: "fr", strength: 1 } }
)
Specify hint
for Delete Operations指定删除操作的hint
hint
for Delete OperationsNew 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.members.deleteMany(
{ "points": { $lte: 20 }, "status": "P" },
{ hint: { status: 1 } }
)
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
字段指示使用索引的操作数。