Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
61 changes: 59 additions & 2 deletions source/crud/query/distinct.txt
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,68 @@ of the ``department`` field by using the ``Distinct()`` method:

[English Geology]

.. _golang-distinct-usage-example:

Retrieve Distinct Values Example: Full File
-------------------------------------------

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

This example performs the following actions on the ``restaurant``
collection:

- Matches documents in which the value of the ``cuisine`` field is ``"Tapas"``
- Returns distinct values of the ``borough`` field from the matched documents

.. tabs::

.. tab:: Struct
:tabid: structExample

The following code uses a struct to retrieve distinct values of the
``borough`` field for documents in the ``restaurants`` collection that match
the specified filter:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: since you already described the code example above, I think you can simplify this description to something like:

Suggested change
The following code uses a struct to retrieve distinct values of the
``borough`` field for documents in the ``restaurants`` collection that match
the specified filter:
The following code uses a struct to retrieve distinct ``borough`` field values of the matching documents:

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applies to the bson.D tab as well

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm actually fine with restating the purpose of the code example in a bit more detail here. Mostly because people skim, and it might be helpful for bots to have the description right above the code example.


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

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

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

Brooklyn
Manhattan
Queens

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

The following code uses a bson.D type to retrieve distinct values of the
``borough`` field for documents in the ``restaurants`` collection that match
the specified filter:

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

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

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

Brooklyn
Manhattan
Queens

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

For a runnable example that retrieves distinct values, see :ref:`golang-distinct-usage-example`.

To learn about constructing a query filter, see :ref:`golang-query-document`.

API Documentation
Expand Down
35 changes: 25 additions & 10 deletions source/includes/usage-examples/code-snippets/distinct.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,25 +48,25 @@ func main() {
}
}()

// begin distinct
coll := client.Database("sample_mflix").Collection("movies")
filter := bson.D{{"directors", "Natalie Portman"}}
// Filters the collection for documents where the value of cuisine is "Tapas"
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := RestaurantCuisineFilter{Cuisine: "Tapas"}

// Retrieves the distinct values of the "title" field in documents
// Retrieves the distinct values of the "borough" field in documents
// that match the filter
var arr []string
err = coll.Distinct(context.TODO(), "title", filter).Decode(&arr)
err = coll.Distinct(context.TODO(), "borough", filter).Decode(&arr)
if err != nil {
panic(err)
}
// end distinct

// Prints the distinct "title" values
// Prints the distinct "borough" values
for _, result := range arr {
fmt.Println(result)
}

// When you run this file, it should print:
// A Tale of Love and Darkness
// New York, I Love You
// Brooklyn
// Manhattan
// Queens
Comment on lines +64 to +66
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: up to you, but since you show the sample output I don't think you need this section in the code file

Copy link
Collaborator Author

@lindseymoore lindseymoore Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Talked with Stephanie, and we agreed it was best to keep them in! In the case where users copy the code out of their own terminal, they can have the output easily accessible.

}
57 changes: 57 additions & 0 deletions source/includes/usage-examples/code-snippets/distinctBsonD.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Retrieves distinct values of a field 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)
}
}()

// Filters the collection for documents where the value of cuisine is "Tapas"
coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"cuisine", "Tapas"}}

// Retrieves the distinct values of the "borough" field in documents
// that match the filter
var arr []string
err = coll.Distinct(context.TODO(), "borough", filter).Decode(&arr)
if err != nil {
panic(err)
}

// Prints the distinct "borough" values
for _, result := range arr {
fmt.Println(result)
}

// When you run this file, it should print:
// Brooklyn
// Manhattan
// Queens
}
Loading