对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

计算文档方法示例

可以使用 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 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字段中包含“中国”

注意

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

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