“文档” 菜单
文档首页
/ / /
Go 驱动程序
/

计算文档

您可以使用 EstimatedDocumentCount()方法获得collection中文档数量的近似值,并使用CountDocuments()方法获得collection中文档的确切数量。

提示

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

以下示例对 movies 集合执行以下操作:

  • 集合中文档的近似数量

  • 计算 countries 包含“China”的文档数量

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 collection中有303个文档在countries字段中包含“中国”

注意

文档的确切数量可能因您的数据集而异。

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

← 监控数据变化