Docs Menu
Docs Home
/
PHP Library Manual
/ /

Retrieve Distinct Field Values

In this guide, you can learn how to use the MongoDB PHP Library to retrieve the distinct values of a specified field across a collection.

Within a collection, different documents might contain different values for a single field. For example, one document in a restaurants collection has a borough value of 'Manhattan', and another has a borough value of 'Queens'. By using the MongoDB PHP Library, you can retrieve all the unique values that a field contains across multiple documents in a collection.

The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your PHP application, instantiate a MongoDB\Client that connects to an Atlas cluster and assign the following value to your $collection variable:

$collection = $client->sample_restaurants->restaurants;

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

To retrieve the distinct values for a specified field, call the MongoDB\Collection::distinct() method and pass in the name of the field you want to find distinct values for.

The following example retrieves the distinct values of the borough field in the restaurants collection:

$results = $collection->distinct('borough', []);
foreach ($results as $value) {
echo json_encode($value), PHP_EOL;
}
"Bronx"
"Manhattan"
"Missing"
"Queens"
"Staten Island"

The operation returns an array that stores each distinct borough field value. Although several documents have the same value in the borough field, each value appears in the results only once.

You can provide a query filter to the distinct() method to find the distinct field values across a subset of documents in a collection. A query filter is an expression that specifies search criteria used to match documents in an operation. For more information about creating a query filter, see the Specify a Query guide.

The following example retrieves the distinct values of the borough field for all documents that have a cuisine field value of 'Italian':

$results = $collection->distinct('borough', ['cuisine' => 'Italian']);
foreach ($results as $value) {
echo json_encode($value), PHP_EOL;
}
"Bronx"
"Manhattan"
"Queens"
"Staten Island"

You can modify the behavior of the distinct() method by passing an array that specifies option values. The following table describes some options you can set to customize the operation:

Option
Description

collation

The collation to use for the operation. To learn more, see the Collation section of this page.
Type: array|object

maxTimeMS

The maximum amount of time in milliseconds that the operation can run.
Type: integer

comment

The comment to attach to the operation.
Type: any valid BSON type

readPreference

The read preference to use for the operation. To learn more, see Read Preference in the Server manual.
Type: MongoDB\Driver\ReadPreference

hint

The index to use for the operation.
Type: string|object

The following example retrieves the distinct values of the name field for all documents that have a borough field value of 'Bronx' and a cuisine field value of 'Pizza'. It also specifies the comment field in an options array to add a comment to the operation:

$query = ['borough' => 'Bronx', 'cuisine' => 'Pizza'];
$options = ['comment' => 'Bronx pizza restaurants'];
$results = $collection->distinct('name', $query, $options);
foreach ($results as $value) {
echo json_encode($value), PHP_EOL;
}
"$1.25 Pizza"
"18 East Gunhill Pizza"
"2 Bros"
"Aenos Pizza"
"Alitalia Pizza Restaurant"
"Amici Pizza And Pasta"
"Angie'S Cafe Pizza"
...

To specify a collation for your operation, pass an $options array parameter that sets the collation option to the operation method. Assign the collation option to an array that configures the collation rules.

The following table describes the fields you can set to configure the collation:

Field
Description

locale

(Required) Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server manual.

Data Type: string

caseLevel

(Optional) Specifies whether to include case comparison.

When set to true, the comparison behavior depends on the value of the strength field:

- If strength is 1, the PHP library compares base
characters and case.

- If strength is 2, the PHP library compares base
characters, diacritics, other secondary differences, and case.

- If strength is any other value, this field is ignored.

When set to false, the PHP library doesn't include case comparison at strength level 1 or 2.

Data Type: bool
Default: false

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: string
Default: "off"

strength


Data Type: int
Default: 3

numericOrdering

(Optional) Specifies whether the driver compares numeric strings as numbers.

If set to true, the PHP library compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the library uses the strings' numeric values and treats "10" as greater than "2".

If set to false, the PHP library compares numeric strings as strings. For example, when comparing the strings "10" and "2", the library compares one character at a time and treats "10" as less than "2".

For more information, see Collation Restrictions in the MongoDB Server manual.

Data Type: bool
Default: false

alternate

(Optional) Specifies whether the library considers whitespace and punctuation as base characters for comparison purposes.

Data Type: string
Default: "non-ignorable"

maxVariable

(Optional) Specifies which characters the library considers ignorable when the alternate field is set to "shifted".

Data Type: string
Default: "punct"

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: bool
Default: false

To learn more about collation and the possible values for each field, see the Collation entry in the MongoDB Server manual.

To learn more about the distinct() method, see MongoDB\Collection::distinct() in the API documentation.

Back

Count Documents

On this page