计算文档数
概述
在本指南中,您可以学习如何获取精确 和 估算 计数,以了解您的集合中文档的数量。
示例数据
本节中的示例使用以下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)
提示
不存在的数据库和集合
当您执行写操作而必要的数据库和集合不存在时,服务器会隐式创建它们。
每个文档描述了一种茶类型及其评分。这些条目对应于 type
和 rating
字段。
准确计数
为了计算符合您查询过滤器的文档数量,请使用 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 |
示例
以下示例计算评分小于 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)
Number of documents with a rating less than six: 4
聚合
您还可以在聚合管道中包含 $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) }
[{counted_documents 5}]
估计文档数量
为了估计您集合中的文档数量,请使用 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)
Estimated number of documents in the tea collection: 9
附加信息
要了解更多关于所述操作的信息,请参阅以下指南
API 文档
要了解更多关于本指南中讨论的任何方法或类型的信息,请参阅以下 API 文档