Docs Menu
Docs Home
/ / /
Go Driver
/

Retrieve Distinct Values of a Field

You can retrieve a list of distinct values for a field across a collection by using the Distinct() method.

Tip

Read the Usage Examples to learn how to run this example.

The following example performs the following on the movies collection:

  • Matches documents in which the directors array contains "Natalie Portman"

  • Returns distinct values of the title from the matched documents

coll := client.Database("sample_mflix").Collection("movies")
filter := bson.D{{"directors", "Natalie Portman"}}
// Retrieves the distinct values of the "title" field in documents
// that match the filter
var arr []string
err = coll.Distinct(context.TODO(), "title", filter).Decode(&arr)
if err != nil {
panic(err)
}

View a fully runnable example

After you run the full example, it prints a slice that contains the following values:

A Tale of Love and Darkness
New York, I Love You

To learn more about retrieving distinct values, see Retrieve Distinct Values.

Distinct()

← Count Documents