Overview
本指南中,您可以了解如何获取集合中文档数量 accurate 和估计计数。
样本数据
本指南中的示例使用名为 students 的集合中的以下文档:
{ "_id": 1, "name": "Jonathon Howard ", "finalGrade": 87.5 } { "_id": 2, "name": "Keisha Freeman", "finalGrade": 12.3 } { "_id": 3, "name": "Wei Zhang", "finalGrade": 99.0 } { "_id": 4, "name": "Juan Gonzalez", "finalGrade": 85.5 } { "_id": 5, "name": "Erik Trout", "finalGrade": 72.3 } { "_id": 6, "name": "Demarcus Smith", "finalGrade": 88.8 }
以下 Student 类对此集合中的文档进行建模:
public class Student { public int Id { get; set; } public string Name { get; set; } public double FinalGrade { get; set; } }
注意
students 集合中的文档使用驼峰命名约定。本指南中的示例使用 ConventionPack 将集合中的字段反序列化为 Pascal 语句,然后映射到 Student 类中的属性。
如需了解有关自定义序列化的更多信息,请参阅自定义序列化。
准确计数
要统计与您的查询筛选器匹配的文档数量,请使用 CountDocuments() 方法。如果传递空查询筛选器,则该方法将返回集合中的文档总数。
例子
以下示例计算其中的 finalGrade 值小于 80 的文档数:
var filter = Builders<Student>.Filter.Lt(s => s.FinalGrade, 80.0); var count = _myColl.CountDocuments(filter); Console.WriteLine("Number of documents with a final grade less than 80: " + count);
Number of documents with a final grade less than 80: 2
修改行为
您可以通过将 CountOptions 类型作为参数传入来修改 CountDocuments() 的行为。如果不指定任何选项,驱动程序将使用默认值。
您可以在 CountOptions 对象中设置以下属性:
属性 | 说明 |
|---|---|
| The type of language collation to use when sorting results. Default: null |
| The index to use to scan for documents to count. Default: null |
| The maximum number of documents to count. Default: 0 |
| The maximum amount of time that the query can run on the server. Default: null |
| The number of documents to skip before counting. Default: 0 |
提示
当你使用 CountDocuments() 返回集合中的文档总数时,MongoDB 会执行集合扫描。你可以使用提示来利用 _id 字段的内置索引,从而避免集合扫描并改进此方法的性能。仅当使用空查询参数调用 CountDocuments() 时才使用此技术。
var filter = Builders<Student>.Filter.Empty; CountOptions opts = new CountOptions(){Hint = "_id_"}; var count = collection.CountDocuments(filter, opts);
预计数量
要估计集合中的文档总数,请使用 EstimatedDocumentCount() 方法。
注意
EstimatedDocumentCount() 方法比 CountDocuments() 方法更高效,因为它会使用集合的元数据而不是扫描整个集合。
修改行为
您可以通过将 EstimatedDocumentCountOptions 类型作为参数传入来修改 EstimatedDocumentCount() 的行为。如果不指定任何选项,驱动程序将使用默认值。
您可以在 EstimatedDocumentCountOptions 对象中设置以下属性:
属性 | 说明 |
|---|---|
| The maximum amount of time that the query can run on the server. Default: null |
例子
以下示例估计了 students 集合中的文档数量:
var count = _myColl.EstimatedDocumentCount(); Console.WriteLine("Estimated number of documents in the students collection: " + count);
Estimated number of documents in the students collection: 6
聚合(Aggregation)
您可以使用 Count() 构建其方法来计算聚合管道中的文档数量。
例子
以下示例执行以下动作:
指定匹配阶段,以查找
FinalGrade值大于80的文档统计符合条件的文档数量
var filter = Builders<Student> .Filter.Gt(s => s.FinalGrade, 80); var result = _myColl.Aggregate().Match(filter).Count(); Console.WriteLine("Number of documents with a final grade more than 80: " + result.First().Count);
Number of documents with a final grade more than 80: 4
更多信息
要了解有关提到的操作的更多信息,请参阅以下指南:
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: