文档菜单
文档首页
/ / /
Java 同步驱动程序
/

计算文档数量

MongoCollection 类中,有两个实例方法可以调用,用于计算集合中的文档数量

  • countDocuments() 返回匹配指定查询的文档数量。如果您指定一个空查询过滤器,该方法将返回集合中的文档总数。

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

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

提示

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

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

调用 countDocuments() 方法时,您可以可选地传递一个 查询过滤器 参数。调用 estimatedDocumentCount() 时不能传递任何参数。

重要

稳定API V1和MongoDB服务器问题

如果您使用的是带有“strict”选项的稳定API V1 以及版本在5.0.0至5.0.8(含)之间的MongoDB服务器,则调用 estimatedDocumentCount() 方法可能会由于服务器错误而产生错误。

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

您还可以向这两个方法中的任何一个传递一个可选参数以指定调用行为

方法
可选参数类
描述
countDocuments()
CountOptions
您可以通过使用 limit() 方法或使用 maxTime() 方法指定最大执行时间来指定要计数的最大文档数。
estimatedDocumentCount()
EstimatedDocumentCountOptions
您可以通过使用 maxTime() 方法指定最大执行时间。

这两个方法都返回匹配文档数量的 long 原始类型。

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

注意

此示例通过连接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文档

返回

监控变化