Docs 菜单
Docs 主页
/ /

计算文档

在本指南中,您可以学习如何使用Ruby驱动程序来检索集合中文档数量的准确估计数。以下方法对集合中的文档进行计数:

  • count_documents:返回与查询过滤匹配或存在于集合中的文档的确切数量

  • estimated_document_count:返回集合中存在的文档的估计数量

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

database = client.use('sample_training')
collection = database['companies']

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅MongoDB入门指南。

使用count_documents方法计算集合中的文档数量。 要计算匹配特定搜索条件的文档数量,请将查询过滤传递给count_documents方法。

提示

要学习;了解有关指定查询的更多信息,请参阅《 指定查询》指南。

要返回集合中所有文档的计数,请调用 count_documents 方法而不传递查询过滤,如以下示例所示:

result = collection.count_documents
puts "Number of documents: #{result}"
Number of documents: 9500

要返回匹配特定搜索条件的文档计数,请将查询过滤传递给count_documents方法。

以下示例计算founded_year字段的值为2010的文档数量:

result = collection.count_documents(founded_year: 2010)
puts "Number of companies founded in 2010: #{result}"
Number of companies founded in 2010: 33

您可以通过传递指定选项值的第二个参数来修改 count_documents 方法的行为。下表描述了可设立自定义计数操作的选项:

选项
说明

collation

The collation to use for the operation.
Type: Hash

hint

The index to use for the operation.
Type: Hash

comment

The comment to attach to the operation.
Type: Object

limit

The maximum number of documents to count. This value must be a positive integer.
Type: Integer

max_time_ms

The maximum amount of time in milliseconds that the operation can run.
Type: Integer

skip

The number of documents to skip before counting documents.
Type: Integer

read

The read preference to use for the operation. To learn more, see Read Preference in the MongoDB Server manual.
Type: Hash

以下示例使用count_documents方法计算number_of_employees字段值为50的文档数量,并指示操作最多计算100结果:

result = collection.count_documents({ number_of_employees: 50 }, limit: 100)
puts "Number of companies with 50 employees: #{result}"
Number of companies with 50 employees: 100

重要

将选项参数传递给 count_documents 方法时,必须将查询过滤括在方括号 ({}) 中。

您可以通过调用estimated_document_count方法来检索集合中文档数量的估计值。 该方法根据集合元数据估计文档数量,这可能比执行精确计数更快。

以下示例估计集合中的文档数量:

result = collection.estimated_document_count
puts "Estimated number of documents: #{result}"
Estimated number of documents: 9500

您可以通过传递指定选项值的参数来修改 estimated_document_count 方法的行为。下表描述了可设立用于自定义操作的选项:

选项
说明

comment

The comment to attach to the operation.
Type: Object

max_time_ms

The maximum amount of time in milliseconds that the operation can run.
Type: Integer

read

The read concern to use for the operation. To learn more, see Read Concern in the MongoDB Server manual.
Type: Hash

以下示例使用estimated_document_count方法返回集合中文档数量的估计值,并将操作超时设置为1000毫秒:

result = collection.estimated_document_count(max_time_ms: 1000)
puts "Estimated number of documents: #{result}"
Estimated number of documents: 9500

要进一步了解本指南所讨论的任何方法,请参阅以下 API 文档:

后退

非重复字段值

在此页面上