文档菜单
文档首页
/ / /
Go 驱动
/

计数文档

您可以使用 EstimatedDocumentCount() 方法来估计集合中文档的数量,使用 CountDocuments() 方法来获取集合中文档的确切数量。EstimatedDocumentCount() 方法

提示

阅读使用示例 了解如何运行此示例。

以下示例在 movies 集合上执行以下操作

  • 估计集合中文档的数量

  • 计算包含 "China" 的 countries 字段的文档数量

coll := client.Database("sample_mflix").Collection("movies")
// Specifies a filter to match documents where the "countries" array
// includes a value of "China"
filter := bson.D{{"countries", "China"}}
// Retrieves and prints the estimated number of documents in the collection
estCount, estCountErr := coll.EstimatedDocumentCount(context.TODO())
if estCountErr != nil {
panic(estCountErr)
}
// Retrieves and prints the number of documents in the collection
// that match the filter
count, err := coll.CountDocuments(context.TODO(), filter)
if err != nil {
panic(err)
}

查看可运行的完整示例

运行完整示例后,你应该看到以下内容

  • movies 集合中大约有 23541 份文档

  • movies 集合中,包含 countries 字段中 "China" 的文档有 303

注意

具体文档数量可能因数据集而异。

要了解更多关于计数文档的信息,请参阅 计数文档。

返回

监控数据变化