Database Manual / Reference / mongosh Methods / Collections

db.collection.deleteOne() (mongosh method方法)

Definition定义

db.collection.deleteOne()

Removes a single document from a collection.从集合中删除单个文档。

Returns:返回A document containing: 包含以下内容的文件:
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled如果操作在写入关注下运行,则布尔值acknowledgedtrue,如果写入关注被禁用,则acknowledgedfalse
  • deletedCount containing the number of deleted documents包含已删除文档的数量

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 deleteOne() method has the following form:deleteOne()方法具有以下形式:

db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string>,
maxTimeMS: <int>,
let: <document>
}
)

The deleteOne() method takes the following parameters:deleteOne()方法接受以下参数:

Parameter参数Type类型Description描述
filterdocument文档

Specifies deletion criteria using a query predicate.使用查询谓词指定删除条件。

Specify an empty document { } to delete the first document returned in the collection.指定一个空文档{ }以删除集合中返回的第一个文档。

writeConcerndocument文档

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.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写关注

collationdocument文档

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: {
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. 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.不能为操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一个排序规则,对排序使用另一个。

hintdocument文档

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

maxTimeMSinteger整数

Optional. 可选。Specifies the time limit in milliseconds for the delete operation to run before timing out.<指定删除操作在超时前运行的时间限制(以毫秒为单位)</p>

letDocument文档

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>. For example: $$targetTotal.要在命令中访问变量的值,请使用双美元符号前缀($$)和变量名,格式为$$<variable_name>。例如:$$targetTotal

To use a variable to filter results, you must access the variable within the $expr operator.要使用变量筛选结果,您必须在$expr运算符中访问该变量。

For a complete example using let and variables, see Update with let Variables.有关使用let和变量的完整示例,请参阅使用let变量更新

Behavior行为

Deletion Order删除顺序

db.collection.deleteOne() deletes the first document that matches the filter. Use a field that is part of a unique index such as _id for precise deletions.删除与筛选器匹配的第一个文档。使用唯一索引(如_id)中的字段进行精确删除。

Sharded Collections分片化集合

To use db.collection.deleteOne() on a sharded collection:要在分片集合上使用db.collection.deleteOne(),请执行以下操作:

  • If you only target one shard, you can use a partial shard key in the query specification.如果只针对一个分片,则可以在查询规范中使用部分分片键。
  • You do not need to provide the shard key or _id field in the query specification, because deleteOne() inherently uses a limit of 1.您不需要在查询规范中提供分片键_id字段,因为deleteOne()固有地使用1的限制。

Transactions事务

db.collection.deleteOne() 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大小限制),另请参阅生产注意事项

Oplog Entries操作日志条目

If a db.collection.deleteOne() operation successfully deletes a document, the operation adds an entry on the oplog (operations log). 如果db.collection.deleteOne()操作成功删除文档,则该操作会在oplog(操作日志)上添加一个条目。If the operation fails or does not find a document to delete, the operation does not add an entry on the oplog.如果操作失败或找不到要删除的文档,则操作不会在oplog上添加条目。

Examples示例

Delete a Single Document删除单个文档

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 the order with _id: ObjectId("563237a41a4d68582c2509da") :以下操作将删除_id: ObjectId("563237a41a4d68582c2509da")的订单:

try {
db.orders.deleteOne( { _id: ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
print(e);
}

The operation returns:操作返回:

{ acknowledged: true, deletedCount: 1 }

The following operation deletes the first document with expiryts greater than ISODate("2015-11-01T12:40:15Z")以下操作删除expiryts(过期)时间大于ISODate("2015-11-01T12:40:15Z")的第一个文档。

try {
db.orders.deleteOne( { expiryts: { $lt: ISODate("2015-11-01T12:40:15Z") } } );
} catch (e) {
print(e);
}

The operation returns:操作返回:

{ acknowledged: true, deletedCount: 1 }

deleteOne() with a Timeout and Query Variables带超时和查询变量的deleteOne()

The following operation deletes the document that matches the type buy-limit, limit is less that the variable priceThreshold, and sets a time limit of 3 seconds:以下操作删除与类型buy-limit匹配的文档,limit小于变量priceThreshold,并设置3秒的时间限制:

try {
db.orders.deleteOne(
{ type: "buy-limit" },
{ $expr: { $eq: ["$limit", "$$priceThreshold"] } },
{
let: { priceThreshold: 49.00 },
maxTimeMS: 3000
}
);
} catch (e) {
print(e);
}

The operation returns:操作返回:

{ acknowledged: true, deletedCount: 1 }

deleteOne() with Write ConcerndeleteOne()与写入关注

Given a three member replica set, the following operation specifies a w of majority, wtimeout of 100:给定一个由三个成员组成的副本集,以下操作指定wmajoritywtimeout100

try {
db.orders.deleteOne(
{ _id: ObjectId("563237a41a4d68582c2509da") },
{ 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 restaurants collection has the following documents:restaurants集合有以下文件:

db.restaurants.insertMany( [
{ _id: 1, category: "café", status: "Open" },
{ _id: 2, category: "cafe", status: "open" },
{ _id: 3, category: "cafE", status: "open" }
] )

The following operation includes the collation option:以下操作包括collation选项:

db.restaurants.deleteOne(
{ category: "cafe", status: "Open" },
{ collation: { locale: "fr", strength: 1 } }
)

The delete filter specifies a collation with strength: 1, which means the collation ignores differences between case and letter variants. 删除筛选器指定了一个strength: 1的排序规则,这意味着排序规则忽略了大小写和字母变体之间的差异。As a result, even though there is not a document that has an exact match with the specified case and letter variants in the filter, the operation still matches and deletes a document.因此,即使没有与筛选器中指定的大小写和字母变体完全匹配的文档,该操作仍然会匹配并删除文档。

Specify hint for Delete Operations指定删除操作的hint

In mongosh, create a students collection with the following documents:mongosh中,使用以下文档创建一个students集合:

db.members.insertMany( [
{ _id: 1, student: "Richard", grade: "F", points: 0 },
{ _id: 2, student: "Jane", grade: "A", points: 60 },
{ _id: 3, student: "Adam", grade: "F", points: 0 },
{ _id: 4, student: "Ronan", grade: "D", points: 20 },
{ _id: 5, student: "Noah", grade: "F", points: 0 },
{ _id: 6, student: "Henry", grade: "A", points: 86 }
] )

Create the following index on the collection:在集合上创建以下索引:

db.members.createIndex( { grade: 1 } )

The following delete operation explicitly hints to use the index { grade: 1 }:以下删除操作明确提示使用索引{ grade: 1 }

db.members.deleteOne(
{ points: { $lte: 20 }, grade: "F" },
{ hint: { grade: 1 } }
)

Note

If you specify an index that does not exist, the operation errors.如果指定的索引不存在,则操作会出错。

The delete command returns the following:delete命令返回以下内容:

{ acknowledged: true, deletedCount: 1 }

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字段指示使用索引的操作数。

Tip

To delete multiple documents, see db.collection.deleteMany()要删除多个文档,请参阅db.collection.deleteMany()