Docs 菜单
Docs 主页
/ /

计算文档

在本指南中,您可以学习如何计算MongoDB集合中的文档数量。Node.js驱动程序提供了两种对集合中的文档进行计数的方法:

  • 集合() 返回集合中与指定查询匹配的文档数。如果指定空查询文档,countDocuments() 将返回集合中的文档总数。

  • collection.estimatedDocumentCount() 根据集合元数据返回集合中文档的估计数量。

estimatedDocumentCount()countDocuments() 速度更快,因为此估算会使用集合的元数据,而不是扫描集合。相比之下,countDocuments() 需要更长的时间才能返回,但它提供了文档数量的准确计数并支持指定筛选器。请为您的工作负载选择适当的方法。

为指定要对哪些文档进行计数, countDocuments()接受查询参数。 countDocuments()计算与指定查询匹配的文档的数量。

countDocuments()estimatedDocumentCount() 支持会影响此方法执行的可选设置。有关更多信息,请参阅每种方法的对应参考文档。

提示

使用 countDocuments() 返回集合中的文档总数时,可以通过避免集合扫描来提高性能。为此,请使用提示来利用 _id 字段上的内置索引。仅当使用空查询参数调用 countDocuments() 时才使用此技术。

collection.countDocuments({}).hint("_id");

注意

设置示例

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.

注意

无Typescript特定功能

以下代码示例使用JavaScript。驱动程序没有与此使用案例相关的 TypeScript 特定功能。

以下示例估计了 sample_mflix数据库中 movies集合中的文档数,然后返回 movies集合中 countries字段中包含 Canada 的文档数的准确计数:

1// Count documents in a collection
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 /* Print the estimate of the number of documents in the
16 "movies" collection */
17 const estimate = await movies.estimatedDocumentCount();
18 console.log(`Estimated number of documents in the movies collection: ${estimate}`);
19
20 /* Print the number of documents in the "movies" collection that
21 match the specified query */
22 const query = { countries: "Canada" };
23 const countCanada = await movies.countDocuments(query);
24 console.log(`Number of movies from Canada: ${countCanada}`);
25 } finally {
26 // Close the connection after the operations complete
27 await client.close();
28 }
29}
30// Run the program and print any thrown exceptions
31run().catch(console.dir);

运行上述示例代码会产生以下输出:

Estimated number of documents in the movies collection: 23541
Number of movies from Canada: 1349

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

后退

指定查询

在此页面上