Docs Menu
Docs Home
/ / /
Go Driver
/ / /

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.

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 := []interface{}{
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.

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-nil query 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.

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
SetComment()
Sets a comment to attach to the distinct operation.
Default: nil

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)
[English Geology]

For a runnable example that retrieves 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:

  • Distinct()

  • DistinctOptions

Back

Access Data From a Cursor