Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Java (Sync) 驱动程序

计算文档

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 基元返回匹配文档的数量。

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

注意

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接指南

// Runs count operations on a collection by using the Java driver
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");
try {
// 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);
// Prints a message if any exceptions occur during the operations
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
}
}
}
}

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

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

提示

旧版 API

如果您使用的是传统 API,请参阅我们的常见问题页面,了解需要对该代码示例进行哪些更改。

有关此页面上提及的类和方法的更多信息,请参阅以下 API 文档:

← 注意更改