Overview
在本指南中,您可以学习如何计算MongoDB集合中的文档数量。Node.js驱动程序提供了两种对集合中的文档进行计数的方法:
集合() 返回集合中与指定查询匹配的文档数。如果指定空查询文档,
countDocuments()将返回集合中的文档总数。collection.estimatedDocumentCount() 根据集合元数据返回集合中文档的估计数量。
estimatedDocumentCount() 比 countDocuments() 速度更快,因为此估算会使用集合的元数据,而不是扫描集合。相比之下,countDocuments() 需要更长的时间才能返回,但它提供了文档数量的准确计数并支持指定筛选器。请为您的工作负载选择适当的方法。
为便于指定要对哪些文档进行计数,countDocuments() 接受一个查询参数。countDocuments() 会计算与指定查询匹配的文档数量。
countDocuments() 且 estimatedDocumentCount() 支持会影响此方法执行的可选设置。有关更多信息,请参阅每种方法的对应参考文档。
countDocuments() 示例:完整文件
注意
设置示例
该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。此示例还使用 Atlas 示例数据集 中的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南。 将其加载到 MongoDB Atlas 免费套餐上的数据库中。
注意
无Typescript特定功能
以下代码示例使用JavaScript。驱动程序没有与此使用案例相关的 TypeScript 特定功能。
以下示例估计了 sample_mflix数据库中 movies集合中的文档数,然后返回 movies集合中 countries字段中包含 Canada 的文档数的准确计数:
1 // Count documents in a collection 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async 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 31 run().catch(console.dir);
运行上述示例代码会产生以下输出:
Estimated number of documents in the movies collection: 23541 Number of movies from Canada: 1349
API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: