Count Documents清点文件

Note

If you specify a callback method, countDocuments() and estimatedDocumentCount() return nothing. 如果指定回调方法,countDocuments()estimatedDocumentCount()将不返回任何内容。If you do not specify one, this method returns a Promise that resolves to the result object when it completes. 如果未指定,此方法将返回一个Promise,该Promise在完成时解析为结果对象。See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.有关更多信息,请参阅我们的承诺和回调指南,或参阅API文档以了解有关结果对象的信息。

The Node.js driver provides two methods for counting documents in a collection: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. 相反,countDocuments()返回需要更长的时间,但提供了文档数量的准确计数,并支持指定筛选器。Choose the appropriate method for your workload.为您的工作负载选择合适的方法。

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

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

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集合中加拿大文档数的准确计数。

Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB实例,并与包含示例数据的数据库交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例并加载示例数据集的更多信息,请参阅用法示例指南

import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { await client.connect();
const database = client.db("sample_mflix"); const movies = database.collection("movies");
// Estimate the total number of documents in the collection and print out the count.估计集合中的文档总数并打印计数。 const estimate = await movies.estimatedDocumentCount(); console.log(`Estimated number of documents in the movies collection: ${estimate}`);
// Query for movies from Canada.查询来自加拿大的电影。 const query = { countries: "Canada" };
// Find the number of documents that match the specified query, (i.e. with "Canada" as a value in the "countries" field)查找与指定查询匹配的文档数(即“国家”字段中的值为“加拿大”) // and print out the count.然后把计数打印出来。 const countCanada = await movies.countDocuments(query); console.log(`Number of movies from Canada: ${countCanada}`); } finally { await client.close(); } } run().catch(console.dir);
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { await client.connect();
const database = client.db("sample_mflix"); const movies = database.collection("movies");
// Estimate the total number of documents in the collection // and print out the count. const estimate = await movies.estimatedDocumentCount(); console.log(`Estimated number of documents in the movies collection: ${estimate}`);
// Query for movies from Canada. const query = { countries: "Canada" };
// Find the number of documents that match the specified // query, (i.e. with "Canada" as a value in the "countries" field) // and print out the count. const countCanada = await movies.countDocuments(query); console.log(`Number of movies from Canada: ${countCanada}`); } finally { await client.close(); } } run().catch(console.dir);
Note
Identical Code Snippets相同的代码片段

The JavaScript and TypeScript code snippets above are identical. 上面的JavaScript和TypeScript代码片段是相同的。There are no TypeScript specific features of the driver relevant to this use case.驱动程序没有与此用例相关的特定于TypeScript的特性。

If you run the preceding sample code, you should see the following output:如果运行前面的示例代码,您将看到以下输出:

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