Docs 菜单
Docs 主页
/ / /
Ruby 驱动程序
/

Delete Documents

在本指南中,您可以学习;了解如何使用Ruby驾驶员通过执行删除操作从MongoDB集合中删除文档。

删除操作可从 MongoDB 集合中删除一个或多个文档。 您可以使用 delete_onedelete_many方法执行删除操作。

本指南中的示例使用restaurants sample_restaurantsAtlas示例数据集的 数据库中的Mongo::Client 集合。要从Ruby应用程序访问权限此集合,请创建一个连接到Atlas 集群的 对象,并将以下值分配给databasecollection 变量:

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_onedelete_many 方法,以设立配置删除操作的选项。如果不指定任何选项,驾驶员将使用默认设置执行删除操作。

下表描述了可用于配置删除操作的选项:

选项
说明

collation

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

session

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.

hint

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.

let

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 文档:

后退

Update Documents

在此页面上