db.collection.remove()
On this page本页内容
Deprecated mongosh Method不推荐的mongosh
方法
This method is deprecated in mongosh
. mongosh
中不赞成使用此方法。For alternative methods, see Compatibility Changes with Legacy mongo Shell.有关其他方法,请参阅与传统mongo
Shell的兼容性更改。
Definition定义
db.collection.remove()
-
Removes documents from a collection.从集合中删除文档。Thedb.collection.remove()
method can have one of two syntaxes.db.collection.remove()
方法可以有两种语法之一。Theremove()
method can take a query document and an optionaljustOne
boolean: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
}
)Parameter参数Type类型Description描述query
document Specifies deletion criteria using query operators.使用查询运算符指定删除条件。To delete all documents in a collection, pass an empty document (若要删除集合中的所有文档,请传递一个空文档({}
).{}
)。justOne
boolean Optional.可选的。To limit the deletion to just one document, set to若要将删除限制为仅一个文档,请设置为true
.true
。Omit to use the default value of忽略使用默认值false
and delete all documents matching the deletion criteria.false
并删除所有符合删除条件的文档。writeConcern
document Optional.可选的。A document expressing the write concern.表示写入关注的文档。Omit to use the default write concern. See 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
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.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能为查找使用一个排序规则,为排序使用另一个排序顺序。let
document 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>
.$$
)和形式为$$<variable_name>
的变量名。For example:例如:$$targetTotal
.$$targetTotal
。NoteFor a complete example using有关使用let
and variables, see Use Variables inlet
.let
和变量的完整示例,请参阅在let
中使用变量。
New in version 5.0.5.0版新增。Theremove()
returns an object that contains the status of the operation.remove()
返回一个包含操作状态的对象。Returns:返回值:A WriteResult object that contains the status of the operation.包含操作状态的WriteResult对象。
Behavior行为
Write Concern写入关注
The remove()
method uses the delete
command, which uses the default write concern. remove()
方法使用delete
命令,该命令使用默认的写入关注。To specify a different write concern, include the write concern in the options parameter.要指定不同的写入关注,请在options参数中包含该写入关注。
Query Considerations查询注意事项
By default, 默认情况下,remove()
removes all documents that match the query
expression. remove()
会删除所有与查询表达式匹配的文档。Specify the 指定justOne
option to limit the operation to removing a single document. 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分片集合
All 指定remove()
operations for a sharded collection that specify the justOne: true
option must include the shard key or the _id
field in the query specification.justOne:true
选项的分片集合的所有remove()
操作都必须在查询规范中包括分片键或_id
字段。
在不包含分片键或remove()
operations specifying justOne: true
in a sharded collection which do not contain either the shard key or the _id
field return an error._id
字段的分片集合中指定justOne:true
的remove()
操作返回错误。
Transactions事务
db.collection.remove()
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.有关其他事务使用注意事项(如运行时限制和操作日志大小限制),请参阅生产注意事项。
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 {}
. {}
调用remove
方法。The following operation deletes all documents from the bios collection:以下操作将删除bios
集合中的所有文档:
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. products
中删除qty
大于20的所有文档,并指定写入关注为w:2
、wtimeout
为5000毫秒。This operation either returns after the write propagates to both the primary and one secondary, or times out after 5 seconds.此操作要么在写入传播到主和一个辅助后返回,要么在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
.remove
方法,同时将query
条件和justOne
参数设置为true
或1
。
The following operation removes the first document from the collection 以下操作将从集合products
where qty
is greater than 20
:products
中删除qty
大于20
的第一个文档:
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:以下操作包括collation
选项:
db.myColl.remove(
{ category: "cafe", status: "A" },
{ collation: { locale: "fr", strength: 1 } }
)
Use Variables in let
在let
中使用变量
let
New in version 5.0. 5.0版新增。
To define variables that you can access elsewhere in the command, use the let option.要定义可以在命令的其他地方访问的变量,请使用let
选项。
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 })
See also: 另请参阅:
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" : "WriteConcernFailed",
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : { // Added in MongoDB 4.4
"w" : "majority",
"wtimeout" : 1,
"provenance" : "getLastErrorDefaults"
}
}
}
})
See also: 另请参阅:
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"
}
})