db.collection.deleteOne()

On this page本页内容

Definition定义

db.collection.deleteOne()

mongo Shell Method方法

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. 本页记录了mongo shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。

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

db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>,
      hint: <document|string>        // Available starting in MongoDB 4.4
   }
)
Parameter参数Type类型Description描述
filter document

Specifies deletion criteria using query operators.使用查询运算符指定删除条件。

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

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

New in version 3.4.版本3.4中的新功能。

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.有关示例,请参阅指定删除操作提示

New in version 4.4.版本4.4中的新功能。

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

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)一部分的字段进行精确删除。

Capped Collections封顶集合

db.collection.deleteOne() throws a WriteError exception if used on a capped collection. dbcollectiondeleteOne()如果用于封顶集合,则db.collection.deleteOne()会引发WriteError异常。To remove documents from a capped collection, use db.collection.drop() instead.要从封顶集合中删除文档,请改用db.collection.drop()

Sharded Collections分片集合

db.collection.deleteOne() operations on a sharded collection must include the shard key or the _id field in the query specification. 对分片集合执行的db.collection.deleteOne()操作必须包括查询规范中的分片键_id字段。db.collection.deleteOne() operations in a sharded collection which do not contain either the shard key or the _id field return an error.分片集合中如果不包含分片键_id字段,则执行db.collectiond.eleteOne()操作将返回错误。

Transactions事务

db.collection.deleteOne() 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.要将写关注点用于事务,请参阅事务和写关注点

Important重要的

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.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项

Examples示例

Delete a Single Document删除单个文档

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 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 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 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"
     }
   }
})

Specify Collation指定排序规则

New in version 3.4.版本3.4中的新功能。

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.deleteOne(
   { category: "cafe", status: "A" },
   { collation: { locale: "fr", strength: 1 } }
)

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

New in version 4.4.版本4.4中的新功能。

From the mongo shell, create a members collection with the following documents:mongo shell中,创建包含以下文档的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.deleteOne(
   { "points": { $lte: 20 }, "status": "P" },
   { hint: { status: 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字段指示使用索引的操作数。

See also参阅

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