Docs Menu
Docs Home
/ / /
C#/.NET
/ /

Count Documents

In this guide, you can learn how to get an accurate and estimated count of the number of documents in your collection.

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.

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.

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

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

Collation

The type of language collation to use when sorting results. See the Collation section of this page for more information.
Default: null

Hint

The index to use to scan for documents to count.
Default: null

Limit

The maximum number of documents to count.
Default: 0

MaxTime

The maximum amount of time that the query can run on the server.
Default: null

Skip

The number of documents to skip before counting.
Default: 0

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);

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

locale

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.

If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to "simple".
Data Type: string

Locale

caseLevel

(Optional) Specifies whether to include case comparison.

When this argument is true, the driver's behavior depends on the value of the strength argument:

- If strength is CollationStrength.Primary, the driver compares base characters and case.
- If strength is CollationStrength.Secondary, the driver compares base characters, diacritics, other secondary differences, and case.
- If strength is any other value, this argument is ignored.

When this argument is false, the driver doesn't include case comparison at strength level Primary or Secondary.

Data Type: boolean
Default: false

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Default: CollationStrength.Tertiary

Strength

numericOrdering

(Optional) Specifies whether the driver compares numeric strings as numbers.

If this argument is true, the driver compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the driver treats the values as 10 and 2, and finds 10 to be greater.

If this argument is false or excluded, the driver compares numeric strings as strings. For example, when comparing the strings "10" and "2", the driver compares one character at a time. Because "1" is less than "2", the driver finds "10" to be less than "2".

For more information, see Collation Restrictions in the MongoDB Server manual.

Data Type: boolean
Default: false

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(Optional) Specifies whether the driver normalizes text as needed.

Most text doesn't require normalization. For more information about normalization, see the ICU documentation.

Data Type: boolean
Default: false

Normalization

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

For more information about collation, see the Collation page in the MongoDB Server manual.

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.

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

MaxTime

The maximum amount of time that the query can run on the server.
Default: null

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

You can use the Count() builder method to count the number of documents in an aggregation pipeline.

The following example performs the following actions:

  • Specifies a match stage to find documents with a FinalGrade value greater than 80

  • Counts 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

To learn more about the operations mentioned, see the following guides:

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

Back

Specify Fields to Return

On this page