Definition定义
db.collection.deleteOne()Removes a single document from a collection.从集合中删除单个文档。Returns:返回A document containing:包含以下内容的文件:A boolean如果操作在写入关注下运行,则布尔值acknowledgedastrueif the operation ran with write concern orfalseif write concern was disabledacknowledged为true,如果写入关注被禁用,则acknowledged为falsedeletedCountcontaining 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()方法接受以下参数:
filter |
| |
writeConcern |
| |
collation |
| |
hint |
| |
maxTimeMS |
| |
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(),请执行以下操作:
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:w为majority,wtimeout为100:
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
hint for Delete OperationsIn 在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()