可以使用 EstimatedDocumentCount() 方法获取集合中文档数的近似值,并使用 CountDocuments() 方法获取集合中文档的确切数目。
例子
提示
参阅“使用示例”,了解如何运行此示例。
以下示例对 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 collectionestCount, estCountErr := coll.EstimatedDocumentCount(context.TODO())if estCountErr != nil { panic(estCountErr)}
// Retrieves and prints the number of documents in the collection// that match the filtercount, err := coll.CountDocuments(context.TODO(), filter)if err != nil { panic(err)}查看完全可运行的示例
预期结果
运行完整示例后,您应该会看到以下内容:
movies集合中约有23541个文档moviescollection中有303个文档在countries字段中包含“中国”
注意
文档的确切数量可能因您的数据集而异。
更多信息
要了解有关计数文档的更多信息,请参阅计数文档。