Delete Documents
Overview
在本指南中,您可以学习;了解如何使用MongoDB PHP库通过执行删除操作从MongoDB集合中删除文档。
删除操作可从 MongoDB 集合中删除一个或多个文档。 您可以使用 MongoDB\Collection::deleteOne()
或MongoDB\Collection::deleteMany()
方法执行删除操作。
样本数据
本指南中的示例使用 Atlas示例数据集的sample_restaurants
数据库中的restaurants
集合。 要从PHP应用程序访问权限此集合,请实例化一个连接到Atlas 集群的MongoDB\Client
,并将以下值分配给$collection
变量:
$collection = $client->sample_restaurants->restaurants;
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
删除操作
您可以通过以下方法执行删除操作:
MongoDB\Collection::deleteOne()
,这会删除与 Atlas Search条件匹配的 第一个文档MongoDB\Collection::deleteMany()
,这会删除与 Atlas Search条件匹配的 所有文档
每个删除方法都需要一个查询过滤文档,它指定搜索条件以确定选择要删除的文档。 有关查询筛选器的更多信息,请参阅MongoDB Server手册中的查询筛选器文档部分。
删除一个文档
以下示例使用deleteOne()
方法删除restaurants
集合中name
值为'Ready Penny Inn'
的文档:
$collection->deleteOne(['name' => 'Ready Penny Inn']);
删除多个文档
以下示例使用deleteMany()
方法删除restaurants
集合中borough
值为'Brooklyn'
的所有文档:
$collection->deleteMany(['borough' => 'Brooklyn']);
修改删除操作
您可以通过将指定选项值的大量作为参数传递来修改MongoDB\Collection::deleteOne()
和MongoDB\Collection::deleteMany()
方法的行为。 下表描述了可在大量中设立的选项:
选项 | 说明 |
---|---|
| Specifies the kind of language collation to use when comparing
strings. For more information, see Collation
in the MongoDB Server manual. |
| Sets the write concern for the operation. This option defaults to
the collection's write concern.
For more information, see Write Concern
in the MongoDB Server manual. |
| Gets or sets the index to scan for documents.
For more information, see the hint statement
in the MongoDB Server manual. |
| Specifies a document with a list of values to improve operation readability.
Values must be constant or closed expressions that don't reference document
fields. For more information, see the let statement in the
MongoDB Server manual. |
| Specifies the client session to associate with the operation. For more
information, see Session in the
MongoDB Server manual. |
| Attaches a comment to the operation. For more information, see the delete command
fields guide in the
MongoDB Server manual. |
例子
以下示例调用 deleteMany()
方法删除restaurants
集合中 name
值包含string 'Mongo'
的所有文档。 它还在大量参数中设置comment
选项,以便为操作添加注释:
$collection->deleteMany( ['name' => new MongoDB\BSON\Regex('Mongo')], ['comment' => 'Deleting Mongo restaurants'], );
注意
如果将上示例中的deleteMany()
方法替换为deleteOne()
,则该库仅删除name
值包含'Mongo'
的第一个文档。
返回值
MongoDB\Collection::deleteOne()
和MongoDB\Collection::deleteMany()
方法返回MongoDB\DeleteResult
对象。 该类包含以下成员函数:
isAcknowledged()
,它返回一个布尔值,表示操作是否已确认。getDeletedCount()
,返回已删除的文档数。 如果写入操作未得到确认,则此方法会引发错误。
如果查询过滤与任何文档都不匹配,则驾驶员不会删除任何文档,并且getDeletedCount()
会返回0
。
例子
以下示例调用deleteMany()
方法来删除除cuisine
值为'Greek'
的文档。 然后,它调用getDeletedCount()
成员函数来打印已删除文档的数量:
$result = $collection->deleteMany(['cuisine' => 'Greek']); echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL;
Deleted documents: 111
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: