Overview
In this guide, you can learn how to retrieve distinct values for a specified field across a single collection.
Sample Data
The example in this guide uses the following Course struct as a model for documents in the courses collection:
type Course struct { Title string Department string Enrollment int32 }
To run the example, load the sample data into the db.courses collection with the following snippet:
coll := client.Database("db").Collection("courses") docs := []any{ Course{Title: "World Fiction", Department: "English", Enrollment: 35}, Course{Title: "Abstract Algebra", Department: "Mathematics", Enrollment: 60}, Course{Title: "Modern Poetry", Department: "English", Enrollment: 12}, Course{Title: "Plate Tectonics", Department: "Geology", Enrollment: 30}, } result, err := coll.InsertMany(context.TODO(), docs)
Tip
Nonexistent Databases and Collections
If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.
Each document contains a description of a university course that includes the course title, department, and enrollment. These items correspond to the title, department, and enrollment fields in each document.
Distinct
To retrieve distinct values for a specified field across a single collection, pass the following parameters to the Distinct() method:
The field name for which you want to retrieve the distinct values
A
non-nilquery filter specifying which documents to match
Tip
If you specify an empty query filter, the Distinct() method searches for distinct values across all documents in a collection.
Modify Behavior
You can modify the behavior of the Distinct() method by passing in a DistinctOptions. If you don't specify a DistinctOptions, the driver uses the default values for each option.
The DistinctOptions type allows you to configure options with the following methods:
Method | Description |
|---|---|
| The type of language collation to use when sorting results. |
| Sets a comment to attach to the distinct operation. |
Example
The following example matches documents with an enrollment field value less than 50 and prints the distinct values of the department field by using the Distinct() method:
filter := bson.D{{"enrollment", bson.D{{"$lt", 50}}}} var arr []string err = coll.Distinct(context.TODO(), "department", filter).Decode(&arr) if err != nil { panic(err) } fmt.Printf("%s\n", arr)
Retrieve Distinct Values Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the restaurants collection in the sample_restaurants database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.
This example performs the following actions on the restaurant collection:
Matches documents in which the value of the
cuisinefield is"Tapas"Returns distinct values of the
boroughfield from the matched documents
// 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" ) type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} } 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/ja-jp/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 }
Additional Information
To learn about constructing a query filter, see Specify a Query.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: