Docs Home / Node.js Driver

Count Documents计数文档

Overview概述

In this guide, you can learn how to count the number of documents in your MongoDB collections. The Node.js driver provides two methods for counting documents in a collection:在本指南中,您可以学习如何计算MongoDB集合中的文档数量。Node.js驱动程序提供了两种对集合中的文档进行计数的方法:

  • collection.countDocuments() returns the number of documents in the collection that match the specified query. If you specify an empty query document, countDocuments() returns the total number of documents in the collection.返回集合中与指定查询匹配的文档数。如果指定空查询文档,countDocuments()将返回集合中的文档总数。
  • collection.estimatedDocumentCount() returns an estimation of the number of documents in the collection based on collection metadata.基于集合元数据返回集合中文档数量的估计值

estimatedDocumentCount() is faster than countDocuments() because the estimation uses the collection's metadata rather than scanning the collection. countDocuments()更快,因为估计使用集合的元数据而不是扫描集合。In contrast, countDocuments() takes longer to return, but provides an accurate count of the number of documents and supports specifying a filter. Choose the appropriate method for your workload.相比之下,countDocuments()返回的时间更长,但提供了文档数量的准确计数,并支持指定筛选器。为您的工作量选择合适的方法。

To specify which documents you wish to count, countDocuments() accepts a query parameter. countDocuments() counts the documents that match the specified query.要指定要计数的文档,countsDocuments()接受一个查询参数。countDocuments()对与指定查询匹配的文档进行计数。

countDocuments() and estimatedDocumentCount() support optional settings that affect the method's execution. Refer to the reference documentation for each method for more information.countsDocuments()estimatedDocumentCount()支持影响方法执行的可选设置。有关更多信息,请参阅每种方法的参考文档。

Tip

You can improve performance when using countDocuments() to return the total number of documents in a collection by avoiding a collection scan. 使用countDocuments()返回集合中的文档总数时,可以通过避免集合扫描来提高性能。To do this, use a hint to take advantage of the built-in index on the _id field. Use this technique only when calling countDocuments() with an empty query parameter.为此,使用提示来利用_id字段上的内置索引。仅当使用空查询参数调用countDocuments()时才使用此技术。

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

countDocuments() Example: Full File示例:完整文件

Note

Example Setup示例设置

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. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. 此示例还使用Atlas示例数据集中包含的sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。

Note

No TypeScript Specific Features没有TypeScript特定功能

The following code example uses JavaScript. There are no TypeScript specific features of the driver relevant to this use case.以下代码示例使用JavaScript。驱动程序中没有与此用例相关的TypeScript特定功能。

The following example estimates the number of documents in the movies collection in the sample_mflix database, and then returns an accurate count of the number of documents in the movies collection with Canada in the countries field:以下示例估计sample_mflix数据库中movies集合中的文档数量,然后在countries字段中返回movies集合中加拿大文档数量的准确计数:

// Count documents in a collection清点集合中的文档

import { MongoClient } from "mongodb";

// Replace the uri string with your MongoDB deployment's connection string将uri字符串替换为MongoDB部署的连接字符串
const 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 exceptions运行程序并打印任何抛出的异常
run().catch(console.dir);

Running the preceding sample code results in the following output:运行前面的示例代码会得到以下输出:

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

API Documentation文档

To learn more about any of the types or methods discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下API文档: