Docs Menu

Count Documents

On this page

  • Overview
  • Accurate Count
  • Aggregation
  • Estimated Count
  • Additional Information

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

To run the examples in this guide, load the sample data into the tea.ratings collection with the following snippet:

coll := client.Database("tea").Collection("ratings")
docs := []interface{}{
bson.D{{"type", "Masala"}, {"rating", 10}},
bson.D{{"type", "Matcha"}, {"rating", 7}},
bson.D{{"type", "Assam"}, {"rating", 4}},
bson.D{{"type", "Oolong"}, {"rating", 9}},
bson.D{{"type", "Chrysanthemum"}, {"rating", 5}},
bson.D{{"type", "Earl Grey"}, {"rating", 8}},
bson.D{{"type", "Jasmine"}, {"rating", 3}},
bson.D{{"type", "English Breakfast"}, {"rating", 6}},
bson.D{{"type", "White Peony"}, {"rating", 4}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
Non-existent Databases and Collections

The server implicitly creates the necessary database and collection when you perform a write operation against them if they don't already exist.

Each document contains a rating for a type of tea that corresponds to the type and rating fields.

To count the number of documents that match your query filter, use the CountDocuments() method.

Tip

If you pass an empty query filter, this method returns the total number of documents in the collection.

You can modify the behavior of CountDocuments() by passing in a CountOptions type. If you don't specify any options, the driver uses its default values.

The CountOptions type allows you to configure options with the following methods:

Method
Description
SetCollation()
The type of language collation to use when sorting results.
Default: nil
SetHint()
The index to use to scan for documents to count.
Default: nil
SetLimit()
The maximum number of documents to count.
Default: 0
SetMaxTime()
The maximum amount of time that the query can run on the server.
Default: nil
SetSkip()
The number of documents to skip before counting.
Default: 0

The following example counts the number of documents where the rating is less than 6:

filter := bson.D{{"rating", bson.D{{"$lt", 6}}}}
count, err := coll.CountDocuments(context.TODO(), filter)
if err != nil {
panic(err)
}
fmt.Printf("Number of ratings less than six: %d\n", count)

You can also include the $count stage to count the number of documents in an aggregation pipeline.

The following example performs the following actions:

  • Counts the number of documents where the rating is greater than 5
  • Assigns the count to a field called total_documents
matchStage := bson.D{{"$match", bson.D{{"rating", bson.D{{"$gt", 5}}}}}}
countStage := bson.D{{"$count", "total_documents"}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, countStage})
if err != nil {
panic(err)
}
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}

To estimate the number of documents in your collection, use the EstimatedDocumentCount() method.

Note

The EstimatedDocumentCount() method is quicker 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 in an EstimatedDocumentCountOptions type. If you don't specify any options, the driver uses its default values.

The EstimatedDocumentCountOptions type allows you to configure options with the following methods:

Method
Description
SetMaxTime()
The maximum amount of time that the query can run on the server.
Default: nil

The following example estimates the number of documents in the ratings collection:

count, err := coll.EstimatedDocumentCount(context.TODO())
if err != nil {
panic(err)
}
fmt.Printf("Estimated number of documents in the ratings collection: %d\n", count)

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:

←  Specify a QueryRetrieve Data →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.