Important
Deprecated mongosh Method弃用的mongosh方法
This method is deprecated in mongosh. For alternative methods, see Compatibility Changes with Legacy mongo Shell.mongosh中已弃用此方法。有关替代方法,请参阅与旧版mongo Shell的兼容性更改。
Definition定义
db.collection.remove()Removes documents from a collection.从集合中删除文档。Returns:返回A WriteResult object that contains the status of the operation.包含操作状态的WriteResult对象。
Syntax语法
The db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean:db.collection.remove()方法可以有两种语法之一。remove()方法可以接受一个查询文档和一个可选的justOne布尔值:
db.collection.remove(
<query>,
<justOne>
)
Or the method can take a query document and an optional remove options document:或者,该方法可以接受一个查询文档和一个可选的删除选项文档:
Changed in version 5.0.在版本5.0中的更改。
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>,
collation: <document>,
let: <document> // Added in MongoDB 5.0
}
)
The remove() method takes the following parameters:remove()方法接受以下参数:
query | {}).{})。 | |
justOne | true. Omit to use the default value of false and delete all documents matching the deletion criteria.true。省略使用默认值false,并删除所有符合删除条件的文档。 | |
writeConcern |
| |
collation |
| |
let |
|
Behavior行为
Write Concern写入关注
The remove() method uses the delete command, which uses the default write concern. To specify a different write concern, include the write concern in the options parameter.remove()方法使用delete命令,该命令使用默认的写入关注。要指定不同的写入关注,请将写入关注包含在options参数中。
Query Considerations查询注意事项
By default, 默认情况下,remove() removes all documents that match the query expression. Specify the justOne option to limit the operation to removing a single document. remove()会删除与query表达式匹配的所有文档。指定justOne选项以将操作限制为删除单个文档。To delete a single document sorted by a specified order, use the 要删除按指定顺序排序的单个文档,请使用findAndModify() method.findAndModify()方法。
When removing multiple documents, the remove operation may interleave with other read and/or write operations to the collection.在删除多个文档时,删除操作可能会与对集合的其他读取和/或写入操作交织在一起。
Time Series Collections时间序列集合
You cannot use the 您不能在时间序列集合上使用remove() method on a time series collection.remove()方法。
Sharded Collections分片化集合
To use 要对指定remove() operations for a sharded collection that specify the justOne: true option:justOne: true选项的分片集合使用remove()操作:
Transactions事务
db.collection.remove() 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大小限制),另请参阅生产注意事项。
Examples示例
The following are examples of the 以下是remove() method.remove()方法的示例。
Remove All Documents from a Collection从集合中删除所有文档
To remove all documents in a collection, call the 若要删除集合中的所有文档,请使用空查询文档remove method with an empty query document {}. The following operation deletes all documents from the bios collection:{}调用remove方法。以下操作将从集合中删除所有文档:
db.bios.remove( { } )
This operation is not equivalent to the 此操作并不等同于drop() method.drop()方法。
To remove all documents from a collection, it may be more efficient to use the 要从集合中删除所有文档,使用drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes.drop()方法删除整个集合(包括索引),然后重新创建集合并重建索引可能更有效。
Remove All Documents that Match a Condition删除符合条件的所有文档
To remove the documents that match a deletion criteria, call the 要删除符合删除条件的文档,请使用remove() method with the <query> parameter:<query>参数调用remove()方法:
The following operation removes all the documents from the collection 以下操作将从集合products where qty is greater than 20:products中删除qty大于20的所有文档:
db.products.remove( { qty: { $gt: 20 } } )Override Default Write Concern覆盖默认写入关注
The following operation to a replica set removes all the documents from the collection 以下对副本集的操作将从products where qty is greater than 20 and specifies a write concern of w: 2 with a wtimeout of 5000 milliseconds. This operation either returns after the write propagates to both the primary and one secondary, or times out after 5 seconds.qty大于20的集合products中删除所有文档,并指定w:2的写入关注,wtimeout为5000毫秒。此操作要么在写入传播到主服务器和一个辅助服务器后返回,要么在5秒后超时。
db.products.remove(
{ qty: { $gt: 20 } },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
)Remove a Single Document that Matches a Condition删除符合条件的单个文档
To remove the first document that match a deletion criteria, call the 要删除符合删除条件的第一个文档,请使用remove method with the query criteria and the justOne parameter set to true or 1.query条件调用remove方法,并将justOne参数设置为true或1。
The following operation removes the first document from the collection 以下操作将从products where qty is greater than 20:qty大于20的集合products中删除第一个文档:
db.products.remove( { qty: { $gt: 20 } }, true )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.myColl.remove(
{ category: "cafe", status: "A" },
{ collation: { locale: "fr", strength: 1 } }
)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
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.cakeFlavors.remove(
{ $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
{ let : { targetFlavor: "strawberry" } }
)WriteResult
Successful Results成功的结果
The remove() returns a WriteResult() object that contains the status of the operation. remove()返回一个包含操作状态的WriteResult()对象。Upon success, the 成功后,WriteResult() object contains information on the number of documents removed:WriteResult()对象包含有关删除的文档数量的信息:
WriteResult({ "nRemoved" : 4 })
Write Concern Errors写入关注错误
If the 如果remove() method encounters write concern errors, the results include the WriteResult.writeConcernError field:remove()方法遇到写关注错误,则结果包括WriteResult.writeConcernError字段:
WriteResult({
"nRemoved" : 7,
"writeConcernError" : {
"code" : 64,
"codeName" : "WriteConcernTimeout",
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : {
"w" : "majority",
"wtimeout" : 1,
"provenance" : "getLastErrorDefaults"
}
}
}
})
Errors Unrelated to Write Concern与书写入关注无关的错误
If the 如果remove() method encounters a non-write concern error, the results include WriteResult.writeError field:remove()方法遇到非写入关注错误,则结果包括WriteResult.writeError字段:
WriteResult({
"nRemoved" : 0,
"writeError" : {
"code" : 2,
"errmsg" : "unknown top level operator: $invalidFieldName"
}
})