Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversGo Driver

Count Documents

You can get an approximation on the number of documents in a collection by using the EstimatedDocumentCount() method and an exact number of documents in a collection by using the CountDocuments() method.

Tip

Read the Usage Examples to learn how to run this example.

The following example performs the following on the movies collection:

  • Approximates the number of documents in the collection

  • Counts the number of documents in which the countries contains "China"

coll := client.Database("sample_mflix").Collection("movies")
// Specifies a filter to match documents where the "countries" array
// includes a value of "China"
filter := bson.D{{"countries", "China"}}
// 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)
}

View a fully runnable example

After you run the full example, you should see the following:

  • There are about 23541 documents in the movies collection

  • There are 303 documents in the movies collection that contain "China" in the countries field

Note

The exact number of documents may vary depending on your data set.

To learn more about counting documents, see Count Documents.

←  Monitor Data ChangesRetrieve Distinct Values of a Field →