Docs Menu
Docs Home
/ / /
Go Driver
/ /

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 section use the following Tea struct as a model for documents in the tea collection:

type Tea struct {
Type string
Rating int32
}

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

coll := client.Database("db").Collection("tea")
docs := []interface{}{
Tea{Type: "Masala", Rating: 10},
Tea{Type: "Matcha", Rating: 7},
Tea{Type: "Assam", Rating: 4},
Tea{Type: "Oolong", Rating: 9},
Tea{Type: "Chrysanthemum", Rating: 5},
Tea{Type: "Earl Grey", Rating: 8},
Tea{Type: "Jasmine", Rating: 3},
Tea{Type: "English Breakfast", Rating: 6},
Tea{Type: "White Peony", Rating: 4},
}
result, err := coll.InsertMany(context.TODO(), docs)

Tip

Nonexistent Databases and Collections

If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.

Each document describes a tea type and its rating. These items correspond to the type and rating fields.

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.

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.

opts := options.Count().SetHint("_id_")
count, err := coll.CountDocuments(context.TODO(), bson.D{}, opts)
if err != nil {
panic(err)
}

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

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 documents with a rating less than six: %d\n", count)
Number of documents with a rating less than six: 4

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 in which the value of the rating field is greater than 5

  • Assigns the count to the counted_documents field

matchStage := bson.D{{"$match", bson.D{{"rating", bson.D{{"$gt", 5}}}}}}
countStage := bson.D{{"$count", "counted_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)
}
[{counted_documents 5}]

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 by using the following methods:

Method
Description

SetComment()

Sets a comment to attach to the count operation.
Default: nil

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

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

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Create a MongoClient guide. This example also uses the restaurants collection in the sample_restaurants database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following example performs the following on the restaurants collection:

  • Approximates the number of documents in the collection

  • Counts the number of documents in which the value of the cuisine is "American"

Select the Struct or bson.D tab to see the corresponding code:

The following code uses structs to approximate the number of documents in the collection and count the number of documents in which the value of the cuisine is "American":

// Counts documents in a collection by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
type Restaurant struct {
ID bson.ObjectID `bson:"_id"`
Name string
RestaurantId string `bson:"restaurant_id"`
Cuisine string
Address interface{}
Borough string
Grades interface{}
}
// Creates a filter struct to use for the query
type RestaurantCuisineFilter struct {
Cuisine string
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
// Specifies a filter to match documents where the "cuisine"
// has a value of "American"
filter := RestaurantCuisineFilter{Cuisine: "American"}
// 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)
}
// When you run this file, it should print:
// Estimated number of documents in the movies collection: 25359
// Number of restaurants with American cuisine: 6183
fmt.Printf("Estimated number of documents in the restaurants collection: %d\n", estCount)
fmt.Printf("Number of restaurants with American cuisine: %d\n", count)
}
Estimated number of documents in the restaurants collection: 25359
Number of restaurants with American cuisine: 6183

The following code uses a bson.D type to approximate the number of documents in the collection and count the number of documents in which the value of the cuisine is "American":

// Counts documents in a collection by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
// Specifies a filter to match documents where the "cuisine"
// has a value of "American"
filter := bson.D{{"cuisine", "American"}}
// 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)
}
// When you run this file, it should print:
// Estimated number of documents in the movies collection: 25359
// Number of restaurants with American cuisine: 6183
fmt.Printf("Estimated number of documents in the restaurants collection: %d\n", estCount)
fmt.Printf("Number of restaurants with American cuisine: %d\n", count)
}
Estimated number of documents in the restaurants collection: 25359
Number of restaurants with American cuisine: 6183

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