对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

计算文档

在本指南中,您可以学习;了解如何计算MongoDB集合中的文档数量。MongoCollection 类中有两个实例方法,您可以调用它们来计算集合中的文档数量:

  • countDocuments() 返回集合中与指定查询匹配的文档数。如果指定空查询筛选器,则该方法会返回集合中的文档总数。

  • estimatedDocumentCount() 根据集合元数据返回集合中文档的估计数量。使用此方法时不能指定查询。

estimatedDocumentCount() 方法比 countDocuments() 方法的返回速度更快,因为它使用集合的元数据而不是扫描整个集合。countDocuments() 方法返回文档数量的准确计数并支持指定过滤器。

提示

使用countDocuments() 返回集合中的文档总数时,可以通过避免集合扫描来提高性能。为此,请使用提示来利用 _id字段上的内置索引。仅当使用空查询参数调用countDocuments() 时才使用此技术。

CountOptions opts = new CountOptions().hintString("_id_");
long numDocuments = collection.countDocuments(new BsonDocument(), opts);

调用 countDocuments() 方法时,您可以选择传递查询筛选器参数。您在调用 estimatedDocumentCount() 时不能传递任何参数。

重要

稳定 API V1 和 MongoDB Server 问题

如果您使用的是带有 "strict" 选项的 Stable API V1 ,且 MongoDB Server 版本介于 5.0.0 和 5.0.8(含)之间,则对estimatedDocumentCount()的方法调用可能会因服务器错误而产生错误。

升级到 MongoDB Server 5.0.9 或将 Stable API“strict”选项设置为 false 以避免此问题。

您还可以向其中任何一个方法传递可选参数,指定调用行为:

方法
可选参数类
说明

countDocuments()

CountOptions

您可以使用 limit() 方法指定要统计的最大文档数量,或使用 maxTime() 方法指定最长执行时间。

estimatedDocumentCount()

EstimatedDocumentCountOptions

您可以使用 maxTime() 方法指定最长执行时间。

这两种方法都以 long 基元返回匹配文档的数量。

注意

设置示例

该示例使用连接 URI 连接到 MongoDB 实例。如需学习有关连接到 MongoDB 实例的更多信息,请参阅创建 MongoClient 指南。此示例还使用 Atlas 示例数据集 中的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南。 将其加载到 MongoDB Atlas 免费套餐上的数据库中。

以下示例估计 sample_mflix 数据库中 movies 集合中的文档数,然后返回 movies 集合中 countries 字段中包含 Canada 的文档数的准确计数。

/**
* This file demonstrates how to open a change stream by using the Java driver.
* It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens
* to change events in the "movies" collection. The code uses a change stream with a pipeline
* to only filter for "insert" and "update" events.
*/
package usage.examples;
import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class CountDocuments {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Bson query = eq("countries", "Spain");
// Retrieves and prints the estimated number of documents in the collection
long estimatedCount = collection.estimatedDocumentCount();
System.out.println("Estimated number of documents in the movies collection: " + estimatedCount);
// Retrieves and prints the number of documents with a "countries" value of "Spain"
long matchingCount = collection.countDocuments(query);
System.out.println("Number of movies from Spain: " + matchingCount);
}
}
}

如果运行前面的示例代码,则应看到如下所示的输出(确切的数字可能因数据而异):

Estimated number of documents in the movies collection: 23541
Number of movies from Spain: 755

提示

Legacy API

如果您使用的是旧版API ,请参阅旧版API指南的常见问题解答部分,学习;了解需要对此代码示例进行哪些更改。

有关用于计数文档的类和方法的更多信息,请参阅以下API文档: