Docs Menu

Retrieve Distinct Values

On this page

  • Overview
  • Sample Data
  • Distinct
  • Modify Behavior
  • Additional Information
  • API Documentation

In this guide, you can learn how to retrieve distinct values for a specified field across a single collection.

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

The server implicitly creates the necessary database and collection when you perform a write operation against them if they don't already exist.

Each document contains a rating for a type of tea that corresponds to the type and rating fields.

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.

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

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)
}

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.

To learn more about any of the methods or types discussed in this guide, see the following API Documentation:

←  Access Data From a CursorSort Results →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.