Overview
In this guide, you can learn how to get an accurate and estimated count of the number of documents in your collection.
Sample Data
The examples in this guide use the following documents in a collection called 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 }
The following Student class models the documents in this collection:
public class Student { public int Id { get; set; } public string Name { get; set; } public double FinalGrade { get; set; } }
Note
The documents in the students collection use the camel-case naming convention. The examples in this guide use a ConventionPack to deserialize the fields in the collection into Pascal case and map them to the properties in the Student class.
To learn more about custom serialization, see Custom Serialization.
Accurate Count
To count the number of documents that match your query filter, use the CountDocuments() method. If you pass an empty query filter, this method returns the total number of documents in the collection.
Example
The following example counts the number of documents where the value of finalGrade is less than 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
Modify Behavior
You can modify the behavior of CountDocuments() by passing a CountOptions type as a parameter. If you don't specify any options, the driver uses default values.
You can set the following properties in a CountOptions object:
Property | Description |
|---|---|
| The type of language collation to use when sorting results. See the
Collation section of this page for more information. |
| The index to use to scan for documents to count. |
| The maximum number of documents to count. |
| The maximum amount of time that the query can run on the server. |
| The number of documents to skip before counting. |
Tip
When you use CountDocuments() to return the total number of documents in a collection, MongoDB performs a collection scan. You can avoid a collection scan and improve the performance of this method by using a hint to take advantage of the built-in index on the _id field. Use this technique only when calling CountDocuments() with an empty query parameter.
var filter = Builders<Student>.Filter.Empty; CountOptions opts = new CountOptions(){Hint = "_id_"}; var count = collection.CountDocuments(filter, opts);
Collation
To configure collation for your operation, create an instance of the Collation class.
The following table describes the parameters that the Collation constructor accepts. It also lists the corresponding class property that you can use to read each setting's value.
Parameter | Description | Class Property |
|---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. |
|
| (Optional) Specifies whether to include case comparison. |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. |
|
| (Optional) Specifies which characters the driver considers ignorable when
the |
|
| (Optional) Specifies whether the driver normalizes text as needed. |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. |
|
For more information about collation, see the Collation page in the MongoDB Server manual.
Estimated Count
To estimate the total number of documents in your collection, use the EstimatedDocumentCount() method.
Note
The EstimatedDocumentCount() method is more efficient than the CountDocuments() method because it uses the collection's metadata rather than scanning the entire collection.
Modify Behavior
You can modify the behavior of EstimatedDocumentCount() by passing a EstimatedDocumentCountOptions type as a parameter. If you don't specify any options, the driver uses default values.
You can set the following properties in a EstimatedDocumentCountOptions object:
Property | Description |
|---|---|
| The maximum amount of time that the query can run on the server. |
Example
The following example estimates the number of documents in the students collection:
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
You can use the Count() builder method to count the number of documents in an aggregation pipeline.
Example
The following example performs the following actions:
Specifies a match stage to find documents with a
FinalGradevalue greater than80Counts the number of documents that match the criteria
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
Additional Information
To learn more about the operations mentioned, see the following guides:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: