对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

计算文档

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

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

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

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

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

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

提示

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

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

注意

设置示例

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。

注意

无Typescript特定功能

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

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

// Count documents in a collection import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies"); /* Print the estimate of the number of documents in the "movies" collection */ const estimate = await movies.estimatedDocumentCount(); console.log(`Estimated number of documents in the movies collection: ${estimate}`); /* Print the number of documents in the "movies" collection that match the specified query */ const query = { countries: "Canada" }; const countCanada = await movies.countDocuments(query); console.log(`Number of movies from Canada: ${countCanada}`); } finally { // Close the connection after the operations complete await client.close(); }}// Run the program and print any thrown exceptionsrun().catch(console.dir);

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

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

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