计算文档
Overview
在本指南中,您可以学习;了解如何计算MongoDB集合中的文档数量。 Node.js驾驶员提供了两种对集合中的文档进行计数的方法:
集合() 返回集合中与指定查询匹配的文档数。如果指定空查询文档,则
countDocuments()
将返回集合中的文档总数。collection.estimatedDocumentCount() 根据集合元数据返回集合中文档的估计数量。
estimatedDocumentCount()
比 countDocuments()
速度更快,因为此估算会使用集合的元数据,而不是扫描集合。相比之下,countDocuments()
需要更长的时间才能返回,但它提供了文档数量的准确计数并支持指定筛选器。请为您的工作负载选择适当的方法。
为指定要对哪些文档进行计数, countDocuments()
接受查询参数。 countDocuments()
计算与指定查询匹配的文档的数量。
countDocuments()
且 estimatedDocumentCount()
支持会影响此方法执行的可选设置。有关更多信息,请参阅每种方法的对应参考文档。
提示
使用 countDocuments()
返回集合中的文档总数时,可以通过避免集合扫描来提高性能。为此,请使用提示来利用 _id
字段上的内置索引。仅当使用空查询参数调用 countDocuments()
时才使用此技术。
collection.countDocuments({}).hint("_id");
countDocuments() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到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 文档: