Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

Retrieve Distinct Field Values

On this page

  • Example

You can retrieve distinct field values of documents in a collection by calling the distinct() method on an object collection or a query builder.

To retrieve distinct field values, pass a query filter to the where() method and a field name to the select() method. Then, call distinct() to return the unique values of the selected field in documents that match the query filter.

This usage example performs the following actions:

  • Uses the Movie Eloquent model to represent the movies collection in the sample_mflix database

  • Retrieves distinct field values of documents from the movies collection that match a query filter

  • Prints the distinct values

The example calls the following methods on the Movie model:

  • where(): matches documents in which the value of the directors field includes "Sofia Coppola".

  • select(): retrieves the matching documents' imdb.rating field values.

  • distinct(): retrieves the unique values of the selected field and returns the list of values.

  • get(): retrieves the query results.

$ratings = Movie::where('directors', 'Sofia Coppola')
->select('imdb.rating')
->distinct()
->get();
echo $ratings;

To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.

Tip

For more information about query filters, see the Retrieve Documents that Match a Query section of the Read Operations guide.

← Count Documents

On this page