Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions source/crud/query/count.txt
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,64 @@ The following example estimates the number of documents in the

Estimated number of documents in the tea collection: 9

Count Documents Example: Full File
----------------------------------

.. include:: /includes/usage-examples/example-intro.rst

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 :guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:

.. tabs::

.. tab :: Struct
:tabid: structExample

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":

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/count.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

Estimated number of documents in the restaurants collection: 25359
Number of restaurants with American cuisine: 6183

.. tab :: bson.D
:tabid: bsonDExample

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":

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/countBsonD.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

Estimated number of documents in the restaurants collection: 25359
Number of restaurants with American cuisine: 6183


Additional Information
----------------------

Expand Down
35 changes: 24 additions & 11 deletions source/includes/usage-examples/code-snippets/count.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,29 @@ import (
"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/connect/mongoclient/#environment-variable")
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))
Expand All @@ -33,12 +48,11 @@ func main() {
}
}()

// begin countDocuments
coll := client.Database("sample_mflix").Collection("movies")
coll := client.Database("sample_restaurants").Collection("restaurants")

// Specifies a filter to match documents where the "countries" array
// includes a value of "China"
filter := bson.D{{"countries", "China"}}
// 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())
Expand All @@ -52,11 +66,10 @@ func main() {
if err != nil {
panic(err)
}
// end countDocuments

// When you run this file, it should print:
// Estimated number of documents in the movies collection: 23541
// Number of movies from China: 303
fmt.Printf("Estimated number of documents in the movies collection: %d\n", estCount)
fmt.Printf("Number of movies from China: %d\n", count)
// 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)
}
60 changes: 60 additions & 0 deletions source/includes/usage-examples/code-snippets/countBsonD.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// 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)
}
Loading