在MongoDB中,允许您使用db.collection.deleteOne()方法从集合中删除现有文档。此方法根据过滤器从集合中删除单个文档。
deleteOne()
是一个mongo shell方法,它可以一次更新一个文档。此方法可用于多文档交易中。
- 如果在上限集合中使用此方法,则它将引发异常。
- 此方法删除满足集合中给定条件的第一个文档。换句话说,如果多个文档满足给定条件,则此方法将删除多个文档中与给定过滤器或条件匹配的第一个文档。它不会删除所有与筛选器匹配的文档。
Syntax:
Parameters:
fileter: First parameter of this method. It specifies the selection criteria for the delete using query operators. The type of this parameter is document. If it contains empty document, i.e, {}, then this method will delete the first document from the collection.
Optional Parameters:
- writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is document.
- collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is document.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and deletedCount that represents the total number of deleted documents.
例子:
在以下示例中,我们正在使用:
db.collection.deleteOne(
,
{
writeConcern: ,
collation:
}
)
删除第一个文件:
db.collection.deleteOne()
方法中传递空文档来从贡献者集合中删除第一个文档。
Database: GeeksforGeeks
Collection: contributor
Document: four documents that contain the details of the contributors in the form of field-value pairs.
删除与过滤器匹配的单个文档:
db.collection.deleteOne()
方法从贡献者集合中删除与过滤器匹配的单个文档,即名称:“ Somya”。换句话说,我们正在从数据库中删除名为Somya的贡献者的数据。
删除文件:
在此示例中,我们将从贡献者集合中删除文档。这里有两个文档与过滤器匹配(即语言:“ C#”),因此此方法将删除这两个文档中与过滤器匹配的第一个文档,如下图所示: