Docs Menu

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")
filter := bson.D{{"countries", "China"}}
estCount, estCountErr := coll.EstimatedDocumentCount(context.TODO())
if estCountErr != nil {
panic(estCountErr)
}
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.

←  Watch for ChangesRetrieve Distinct Values of a Field →
Give Feedback
© 2022 MongoDB, Inc.

About

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