Count Documents计数文档
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()
and 和estimatedDocumentCount()
support optional settings that affect the method's execution. 支持影响方法执行的可选设置。Refer to the reference documentation for each method for more information.有关更多信息,请参阅每种方法的参考文档。
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. _id
字段上的内置索引。Use this technique only when calling 仅当使用空查询参数调用countDocuments()
with an empty query parameter.countDocuments()
时才使用此技术。
collection.countDocuments({}, { hint: "_id_" });
Example示例
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
数据库中电影集合中的文档数,然后在countries
字段中返回加拿大电影集合中文档数的准确计数。
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.将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");
//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.查找与指定查询匹配的文档数(即,在“countries”字段中使用“Canada”作为值)并打印出计数。
const countCanada = await movies.countDocuments(query);
console.log(`Number of movies from Canada: ${countCanada}`);
} finally {
await client.close();
}
}
run().catch(console.dir);
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