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"
// 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) }
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.