Definition定义
deleteThedeletecommand removes documents from a collection. A singledeletecommand can contain multiple delete specifications.delete命令用于从集合中删除文档。单个删除命令可以包含多个删除规范。The delete methods provided by the MongoDB drivers use this command internally.MongoDB驱动程序提供的delete方法在内部使用此命令。Changed in version 5.0.在版本5.0中的更改。Tip
In在mongosh, this command can also be run through thedeleteOne(),deleteMany(), andfindOneAndDelete()helper methods.mongosh中,此命令也可以通过deleteOne()、deleteMany()和findOneAndDelete()辅助方法运行。Helper methods are convenient for助手方法对mongoshusers, 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.详见输出。
Compatibility兼容性
This command 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 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:该命令采用以下字段:
delete | ||
deletes | ||
comment |
| |
let |
| |
ordered | 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.true,则当delete语句失败时,返回而不执行其余的delete语句。如果为false,则当delete语句失败时,继续执行其余的delete语句(如果有的话)。默认为true。 | |
writeConcern |
| |
maxTimeMS |
|
Each element of the deletes array contains the following fields:deletes数组的每个元素都包含以下字段:
q | ||
limit | 0 to delete all matching documents or 1 to delete a single document.0以删除所有匹配的文档,或指定1以删除单个文档。 | |
collation |
| |
hint |
|
Behavior行为
Sharded Collections分片化集合
To use 要对指定delete operations for a sharded collection that specify the limit: 1 option:limit:1选项的分片集合使用delete操作,请执行以下操作:
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 distributed transactions.delete可以在分布式事务中使用。
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大小限制),另请参阅生产注意事项。
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:limit: 1从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 }
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: 0从orders集合中删除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. 13个文档。See 详见输出。Output输出 for details.
{ "ok" : 1, "n" : 13 }Delete All Documents from a Collection从集合中删除所有文档
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()。
Delete all documents in the 通过指定空查询条件和orders collection by specifying an empty query condition and a limit of 0:limit:0删除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. See Output for details.35个文档。详见输出。
{ "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 返回的文档显示,该命令在两个delete语句中总共找到并删除了21 documents in total for the two delete statements. 21个文档。See 详见输出。Output输出 for details.
{ "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:以下操作包括collation选项:
db.runCommand({
delete: "myColl",
deletes: [
{ q: { category: "cafe", status: "a" }, limit: 0, 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中,使用以下文档创建一个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 let在let中使用变量
letNew in version 5.0.在版本5.0中新增。
To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let选项。
Note
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.okThe status of the command.命令的状态。
delete.nThe number of documents deleted.已删除的文档数量。
delete.writeErrorsAn array of documents that contains information regarding any error encountered during the delete operation.一组文档,其中包含有关删除操作过程中遇到的任何错误的信息。ThewriteErrorsarray contains an error document for each delete statement that errors.writeErrors数组包含每个出错的delete语句的错误文档。Each error document contains the following information:每个错误文档都包含以下信息:delete.writeErrors.indexAn integer that identifies the delete statement in the一个整数,用于标识deletesarray, which uses a zero-based index.deletes数组中的delete语句,该数组使用从零开始的索引。
delete.writeErrors.codeAn integer value identifying the error.标识错误的整数值。
delete.writeErrors.errmsgA description of the error.错误的描述。
delete.writeConcernErrorDocument describing errors that relate to the write concern.描述与写入关注相关的错误的文档。Changed in version 7.0.6.在版本7.0.6中的更改。 (also available in 6.0.14 and 5.0.30也可在6.0.14和5.0.30中使用): When:当在deleteexecutes onmongos, write concern errors are always reported, even when one or more write errors occur. In previous releases, the occurrence of write errors could cause thedeleteto not report write concern errors.mongos上执行delete时,即使出现一个或多个写入错误,也总是会报告写入关注错误。在以前的版本中,写入错误的发生可能会导致delete操作不报告写入关注错误。ThewriteConcernErrordocuments contian the following fields:writeConcernError文档包含以下字段:delete.writeConcernError.codeAn integer value identifying the cause of the write concern error.一个整数值,用于标识写入关注错误的原因。
delete.writeConcernError.errmsgA description of the cause of the write concern error.写入关注错误原因的描述。
delete.writeConcernError.errInfo.writeConcernThe 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.provenanceA string value indicating where the write concern originated (known as write concern一个字符串值,指示写关注的来源(称为写关注provenance). The following table shows the possible values for this field and their significance:provenance)。下表显示了此字段的可能值及其意义: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.getLastErrorDefaultsfield.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
}