Overview
在本指南中,您可以学习;了解如何使用Ruby驾驶员通过执行删除操作从MongoDB集合中删除文档。
删除操作可从 MongoDB 集合中删除一个或多个文档。 您可以使用 delete_one
或delete_many
方法执行删除操作。
样本数据
本指南中的示例使用restaurants
sample_restaurants
Atlas示例数据集的 数据库中的Mongo::Client
集合。要从Ruby应用程序访问权限此集合,请创建一个连接到Atlas 集群的 对象,并将以下值分配给database
和collection
变量:
database = client.use('sample_restaurants') collection = database[:restaurants]
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
删除操作
您可以使用以下方法在 MongoDB 中执行删除操作:
delete_one
,这会删除与 Atlas Search条件匹配的 第一个文档delete_many
,这会删除与 Atlas Search条件匹配的 所有文档
每种删除方法都需要一个查询过滤参数,该参数指定搜索条件,以确定选择要删除的文档。要学习;了解有关查询筛选器的更多信息,请参阅《 指定查询》指南。
删除一个文档
以下示例使用delete_one
方法删除name
字段值为"Happy Garden"
的文档:
filter = { name: 'Happy Garden' } result = collection.delete_one(filter) puts "Deleted #{result.deleted_count} document(s)"
Deleted 1 document(s)
删除多个文档
以下示例使用delete_many
方法删除borough
字段值为"Brooklyn"
且name
字段值为"Starbucks"
的所有文档:
filter = { name: 'Starbucks', borough: 'Brooklyn' } result = collection.delete_many(filter) puts "Deleted #{result.deleted_count} document(s)"
Deleted 3 document(s)
自定义删除操作
您可以将 Hash
对象作为参数传递给 delete_one
和 delete_many
方法,以设立配置删除操作的选项。如果不指定任何选项,驾驶员将使用默认设置执行删除操作。
下表描述了可用于配置删除操作的选项:
选项 | 说明 |
---|---|
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
| Specifies the session to use for the operation. To learn more about sessions, see
Client Sessions and Causal Consistency Guarantees
in the MongoDB Server manual. |
| Specifies the index to use when matching documents.
For more information, see the hint
option in the delete reference page of the MongoDB Server manual. |
| Provides a map of parameter names and values to set top-level
variables for the operation. Values must be constant or closed
expressions that don't reference document fields. For more information,
see the let option in the delete
reference page of the MongoDB Server manual. |
修改删除示例
以下代码指定 hint
选项来指示删除操作使用 "name_index"
索引。然后,该示例使用 delete_many
方法删除restaurants
集合中 name
字段值包含字符串 "Red"
的所有文档。
filter = { name: /Red/ } options = { hint: 'name_index' } result = collection.delete_many(filter, options) puts "Deleted #{result.deleted_count} document(s)"
Deleted 124 document(s)
提示
如果在上示例中使用delete_one
方法而不是delete_many
方法,则驾驶员仅删除与查询过滤匹配的第一个文档。
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: