文档菜单
文档首页
/ / /
Kotlin 协程
/

计算文档数量

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

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

  • estimatedDocumentCount() 返回基于集合元数据的文档数量的估计。您不能在调用此方法时指定查询。

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

提示

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

val options = CountOptions().hintString("_id_")
val numDocuments = collection.countDocuments(BsonDocument(), options)

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

重要

稳定API V1和MongoDB服务器问题

如果您使用带“严格”选项的稳定API V1 以及版本在5.0.0到5.0.8之间的MongoDB服务器,则调用 estimatedDocumentCount() 方法可能会因服务器错误而出错。

升级到MongoDB服务器5.0.9或将稳定API“严格”选项设置为 false 以避免此问题。

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

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

这两种方法都返回匹配文档的数量,作为 Long 原始类型。

以下示例估计了 sample_mflix 数据库中 movies 集合中的文档数,然后返回具有 countries 字段中的 Spainmovies 集合中文档的确切数量。如果您运行前面的示例代码,您应该看到类似以下内容的输出(确切数字可能因您的数据而异)

注意

此示例使用连接URI连接到MongoDB实例。有关连接到您的MongoDB实例的更多信息,请参阅连接指南.

import com.mongodb.MongoException
import com.mongodb.client.model.Filters
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
data class Movie(val countries: List<String>)
fun main() = runBlocking {
// Replace the uri string with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Movie>("movies")
val query = Filters.eq(Movie::countries.name, "Spain")
try {
val estimatedCount = collection.estimatedDocumentCount()
println("Estimated number of documents in the movies collection: $estimatedCount")
val matchingCount = collection.countDocuments(query)
println("Number of movies from Spain: $matchingCount")
} catch (e: MongoException) {
System.err.println("An error occurred: $e")
}
mongoClient.close()
}
Estimated number of documents in the movies collection: 23541
Number of movies from Spain: 755

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

返回

监视变更