Retrieve Distinct Values
Overview
In this guide, you can learn how to retrieve distinct values for a specified field across a single collection.
Sample Data
To run the examples in this guide, load the sample data into the
tea.ratings
collection with the following
snippet:
coll := client.Database("tea").Collection("ratings") docs := []interface{}{ bson.D{{"type", "Masala"}, {"rating", 10}}, bson.D{{"type", "Matcha"}, {"rating", 7}}, bson.D{{"type", "Masala"}, {"rating", 4}}, bson.D{{"type", "Oolong"}, {"rating", 9}}, bson.D{{"type", "Matcha"}, {"rating", 5}}, bson.D{{"type", "Earl Grey"}, {"rating", 8}}, bson.D{{"type", "Oolong"}, {"rating", 3}}, bson.D{{"type", "Matcha"}, {"rating", 6}}, bson.D{{"type", "Earl Grey"}, {"rating", 4}}, } result, err := coll.InsertMany(context.TODO(), docs) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
Tip
Non-existent 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 rating for a type of tea that corresponds to
the type
and rating
fields.
Distinct
To retrieve distinct values for a specified field across a single
collection, pass the following parameters to the Distinct()
method:
The field name you want distinct values for
A
non-nil
query filter specifying which documents to match
Tip
If you specify an empty query filter, the method matches all the 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 |
---|---|
SetCollation() | The type of language collation to use when sorting results. Default: nil |
SetMaxTime() | The maximum amount of time that the query can run on the server. Default: nil |
Example
The following example matches all documents and prints the distinct values
of the type
field using the Distinct()
method:
results, err := coll.Distinct(context.TODO(), "type", bson.D{}) if err != nil { panic(err) } for _, result := range results { fmt.Println(result) }
Additional Information
For a runnable example of retrieving distinct values, see Retrieve Distinct Values of a Field.
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: