Skip to content

Commit 1a32205

Browse files
committed
DOCSP-41979: Distinct values
1 parent e994533 commit 1a32205

File tree

3 files changed

+201
-1
lines changed

3 files changed

+201
-1
lines changed

source/includes/read/distinct.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
5+
$client = new MongoDB\Client($uri);
6+
7+
// start-db-coll
8+
$db = $client->sample_training;
9+
$collection = $db->companies;
10+
// end-db-coll
11+
12+
// Finds one document with a "name" value of "LinkedIn"
13+
// start-find-one
14+
$document = $collection->findOne(['name' => 'LinkedIn']);
15+
echo json_encode($document) . "\n";
16+
// end-find-one
17+
18+
// Finds documents with a "founded_year" value of 1970
19+
// start-find-many
20+
$results = $collection->find(['founded_year' => 1970]);
21+
// end-find-many
22+
23+
// Prints documents with a "founded_year" value of 1970
24+
// start-cursor
25+
foreach ($results as $doc) {
26+
echo json_encode($doc) . "\n";
27+
}
28+
// end-cursor
29+
30+
// Finds and prints up to 5 documents with a "number_of_employees" value of 1000
31+
// start-modify
32+
$results = $collection->find(
33+
['number_of_employees' => 1000],
34+
['limit' => 5]
35+
);
36+
37+
foreach ($results as $doc) {
38+
echo json_encode($doc) . "\n";
39+
}
40+
// end-modify

source/read.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ Read Data from MongoDB
88
:titlesonly:
99
:maxdepth: 1
1010

11-
/read/retrieve
11+
/read/retrieve
12+
/read/distint

source/read/distinct.txt

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
.. _php-distinct:
2+
3+
==============================
4+
Retrieve Distinct Field Values
5+
==============================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: read, unique, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+php-library+} to retrieve the
24+
distinct values of a specified field across a collection.
25+
26+
Within a collection, different documents might contain different values for a
27+
single field. For example, one document in a ``restaurants`` collection has a
28+
``borough`` value of ``"Manhattan"``, and another has a ``borough`` value of
29+
``"Queens"``. By using the {+php-library+}, you can retrieve all the unique values
30+
that a field contains across multiple documents in a collection.
31+
32+
Sample Data
33+
~~~~~~~~~~~
34+
35+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
36+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
37+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
38+
and assign the following value to your ``collection`` variable:
39+
40+
.. literalinclude:: /includes/read/distinct.php
41+
:language: php
42+
:dedent:
43+
:start-after: start-db-coll
44+
:end-before: end-db-coll
45+
46+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
47+
:atlas:`Get Started with Atlas </getting-started>` guide.
48+
49+
``MongoDB\\Collection::distinct()`` Method
50+
------------------------------------------
51+
52+
To retrieve the distinct values for a specified field, call the ``MongoDB\Collection::distinct()``
53+
method and pass in the name of the field you want to find distinct values for.
54+
55+
Retrieve Distinct Values Across a Collection
56+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
57+
58+
The following example retrieves the distinct values of the ``borough`` field in
59+
the ``restaurants`` collection:
60+
61+
.. io-code-block::
62+
63+
.. input:: /includes/read/distinct.php
64+
:start-after: start-distinct
65+
:end-before: end-distinct
66+
:language: php
67+
:dedent:
68+
69+
.. output::
70+
71+
{ "values" : [ "Bronx", "Brooklyn", "Manhattan", "Missing", "Queens", "Staten Island" ],
72+
"ok" : 1.0, "$clusterTime" : { "clusterTime" : { "$timestamp" : { ... } },
73+
"signature" : { "hash" : { ... }, "keyId" : ... } }, "operationTime" : { "$timestamp" : { ... } }
74+
75+
The operation returns an array that stores each distinct ``borough`` field value. Although
76+
several documents have the same value in the ``borough`` field, each value appears in the
77+
results only once.
78+
79+
Retrieve Distinct Values Across Specified Documents
80+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
81+
82+
You can provide a **query filter** to the ``distinct()`` method to find the distinct
83+
field values across a subset of documents in a collection. A query filter is an expression
84+
that specifies search criteria used to match documents in an operation. For more information
85+
about creating a query filter, see the :ref:`php-specify-query` guide.
86+
87+
The following example retrieves the distinct values of the ``borough`` field for
88+
all documents that have a ``cuisine`` field value of ``'Italian'``:
89+
90+
.. io-code-block::
91+
92+
.. input:: /includes/read/distinct.php
93+
:start-after: start-distinct-with-query
94+
:end-before: end-distinct-with-query
95+
:language: php
96+
:dedent:
97+
98+
.. output::
99+
100+
{ "values" : [ "Bronx", "Brooklyn", "Manhattan", "Queens", "Staten Island" ],
101+
"ok" : 1.0, "$clusterTime" : { "clusterTime" : { "$timestamp" : { ... },
102+
"signature" : { "hash" : { ... }, "keyId" : ... } }, "operationTime" : { "$timestamp" : { ... } }
103+
104+
Modify Distinct Behavior
105+
~~~~~~~~~~~~~~~~~~~~~~~~
106+
107+
You can modify the behavior of the ``MongoDB\Collection::distinct()`` method by
108+
passing an array that specifies option values. The following table describes some
109+
options you can set to customize the operation:
110+
111+
.. list-table::
112+
:widths: 30 70
113+
:header-rows: 1
114+
115+
* - Option
116+
- Description
117+
118+
* - ``collation``
119+
- | The collation to use for the operation.
120+
| **Type**: ``array|object``
121+
122+
* - ``maxTimeMS``
123+
- | The maximum amount of time in milliseconds that the operation can run.
124+
| **Type**: ``integer``
125+
126+
* - ``comment``
127+
- | The comment to attach to the operation.
128+
| **Type**: any valid BSON type
129+
130+
* - ``readPreference``
131+
- | The read preference to use for the operation. To learn more, see
132+
:manual:`Read Preference </core/read-preference/>` in the Server manual.
133+
| **Type**: ``MongoDB\Driver\ReadPreference``
134+
135+
The following example retrieves the distinct values of the ``name`` field for
136+
all documents that have a ``borough`` field value of ``'Bronx'`` and a
137+
``cuisine`` field value of ``'Pizza'``. It also specifies the ``comment`` field
138+
in an options array to add a comment to the operation:
139+
140+
.. io-code-block::
141+
142+
.. input:: /includes/read/distinct.php
143+
:start-after: start-distinct-with-comment
144+
:end-before: end-distinct-with-comment
145+
:language: php
146+
:dedent:
147+
148+
.. output::
149+
150+
{ "values" : [ "$1.25 Pizza", "18 East Gunhill Pizza", "2 Bros", "Aenos Pizza", "Alitalia Pizza Restaurant", … ],
151+
"ok" : 1.0, "$clusterTime" : { "clusterTime" : { … }, "signature" : { … }, "keyId" : … } }, "operationTime" : { … } }
152+
153+
API Documentation
154+
-----------------
155+
156+
To learn more about the ``MongoDB\Collection::distinct()`` method, see the following
157+
API documentation:
158+
159+
- `distinct() <{+api+}/method/MongoDBCollection-distinct/>`__

0 commit comments

Comments
 (0)