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

计算文档

在此页面上

  • 概述
  • 准确计数
  • 聚合(Aggregation)
  • 预计数量
  • 更多信息

本指南中,您可以了解如何获取集合中文档数量 accurate估计计数。

本部分的示例使用以下Tea 结构体作为tea 集合中文档的模型:

type Tea struct {
Type string
Rating int32
}

要运行本指南中的示例,请使用以下代码段将样本数据加载到 db 数据库中的 tea 集合中:

coll := client.Database("db").Collection("tea")
docs := []interface{}{
Tea{Type: "Masala", Rating: 10},
Tea{Type: "Matcha", Rating: 7},
Tea{Type: "Assam", Rating: 4},
Tea{Type: "Oolong", Rating: 9},
Tea{Type: "Chrysanthemum", Rating: 5},
Tea{Type: "Earl Grey", Rating: 8},
Tea{Type: "Jasmine", Rating: 3},
Tea{Type: "English Breakfast", Rating: 6},
Tea{Type: "White Peony", Rating: 4},
}
result, err := coll.InsertMany(context.TODO(), docs)

提示

不存在的数据库和集合

如果执行写操作时不存在必要的数据库和集合,服务器会隐式创建这些数据库和集合。

每个文档都描述了一种茶叶类型及其评级。这些项目对应于 typerating 字段。

要计算与查询筛选器匹配的文档数量,请使用 CountDocuments() 方法。如果传递空查询筛选器,则该方法将返回集合中的文档总数。

提示

当你使用 CountDocuments() 返回集合中的文档总数时,MongoDB 会执行集合扫描。您可以通过使用提示来利用 _id 字段的内置索引,从而避免集合扫描并改进此方法的性能。仅当使用空查询参数调用 CountDocuments() 时才使用此技术。

opts := options.Count().SetHint("_id_")
count, err := coll.CountDocuments(context.TODO(), bson.D{}, opts)
if err != nil {
panic(err)
}

可以通过传入 CountOptions 类型来修改 CountDocuments() 的行为。如果未指定任何选项,驱动程序将使用默认值。

CountOptions 类型允许您使用以下方法配置选项:

方法
说明
SetCollation()
对结果进行排序时要使用的语言排序规则类型。
默认: nil
SetHint()
用于扫描要计数的文档的索引。
默认: nil
SetLimit()
要计数的最大文档数。
默认: 0
SetMaxTime()
查询在服务器上运行的最长时间。
默认: nil
SetSkip()
计数前要跳过的文档。
默认: 0

以下示例计算其中的 rating 小于 6 的文档数:

filter := bson.D{{"rating", bson.D{{"$lt", 6}}}}
count, err := coll.CountDocuments(context.TODO(), filter)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents with a rating less than six: %d\n", count)

您还可以纳入$count阶段来计算聚合管道中的文档数量。

以下示例执行以下动作:

  • 计算 rating 字段的值大于 5 的文档数

  • 将该计数赋值给 counted_documents 字段

matchStage := bson.D{{"$match", bson.D{{"rating", bson.D{{"$gt", 5}}}}}}
countStage := bson.D{{"$count", "counted_documents"}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, countStage})
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

要估计集合中的文档数,请使用 EstimatedDocumentCount() 方法。

注意

EstimatedDocumentCount() 方法比 CountDocuments() 方法更快,因为它使用集合的元数据而不是扫描整个集合。

您可以通过传入 EstimatedDocumentCountOptions 类型来修改 EstimatedDocumentCount() 的行为。如果不指定任何选项,驱动程序将使用默认值。

EstimatedDocumentCountOptions 类型允许您使用以下方法配置选项:

方法
说明
SetMaxTime()
查询在服务器上运行的最长时间。
默认: nil

以下示例估计了 tea 集合中的文档数量:

count, err := coll.EstimatedDocumentCount(context.TODO())
if err != nil {
panic(err)
}
fmt.Printf("Estimated number of documents in the tea collection: %d\n", count)

要了解有关提到的操作的更多信息,请参阅以下指南:

  • 指定查询

  • 跳过返回的结果

  • 限制返回结果的数量

  • 聚合(Aggregation)

  • 排序规则(Collations)

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

← 指定查询