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.
Example
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
Expected Result
After you run the full example, you should see the following:
There are about
23541
documents in themovies
collectionThere are
303
documents in themovies
collection that contain "China" in thecountries
field
Note
The exact number of documents may vary depending on your data set.
Additional Information
To learn more about counting documents, see Count Documents.