Skip to content

Commit 474fc1f

Browse files
authored
DOCSP-41977: Specify documents to return (#105)
* DOCSP-41977: Specify documents to return * edits * code output * toc * MM feedback, code edits * edit * JT feedback * edit * test * MM feedback 2
1 parent cbead21 commit 474fc1f

File tree

3 files changed

+353
-2
lines changed

3 files changed

+353
-2
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
3+
require 'vendor/autoload.php';
4+
5+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
6+
$client = new MongoDB\Client($uri);
7+
8+
// start-db-coll
9+
$collection = $client->sample_restaurants->restaurants;
10+
// end-db-coll
11+
12+
// Retrieves 5 documents that have a "cuisine" value of "Italian"
13+
// start-limit
14+
$cursor = $collection->find(
15+
['cuisine' => 'Italian'],
16+
['limit' => 5]
17+
);
18+
19+
foreach ($cursor as $doc) {
20+
echo json_encode($doc) . PHP_EOL;
21+
}
22+
// end-limit
23+
24+
// Retrieves documents with a "cuisine" value of "Italian" and sorts in ascending "name" order
25+
// start-sort
26+
$cursor = $collection->find(
27+
['cuisine' => 'Italian'],
28+
['sort' => ['name' => 1]]
29+
);
30+
31+
foreach ($cursor as $doc) {
32+
echo json_encode($doc) . PHP_EOL;
33+
}
34+
// end-sort
35+
36+
// Retrieves documents with a "borough" value of "Manhattan" but skips the first 10 results
37+
// start-skip
38+
$cursor = $collection->find(
39+
['borough' => 'Manhattan'],
40+
['skip' => 10]
41+
);
42+
43+
foreach ($cursor as $doc) {
44+
echo json_encode($doc) . PHP_EOL;
45+
}
46+
// end-skip
47+
48+
// Retrieves 5 documents with a "cuisine" value of "Italian", skips the first 10 results,
49+
// and sorts by ascending "name" order
50+
// start-limit-sort-skip
51+
$options = [
52+
'sort' => ['name' => 1],
53+
'limit' => 5,
54+
'skip' => 10,
55+
];
56+
57+
$cursor = $collection->find(['cuisine' => 'Italian'], $options);
58+
foreach ($cursor as $doc) {
59+
echo json_encode($doc) . PHP_EOL;
60+
}
61+
// end-limit-sort-skip
62+
63+
// Returns documents with a "cuisine" value of "Hawaiian" as arrays
64+
// start-return-type
65+
$options = [
66+
'typeMap' => [
67+
'root' => 'array',
68+
'document' => 'array'
69+
]
70+
];
71+
72+
$cursor = $collection->find(['cuisine' => 'Hawaiian'], $options);
73+
foreach ($cursor as $doc) {
74+
print_r($doc) . PHP_EOL;
75+
}
76+
// end-return-type

source/read.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@ Read Data from MongoDB
99
:maxdepth: 1
1010

1111
/read/retrieve
12+
/read/specify-documents-to-return
1213
/read/specify-a-query
13-
/read/project
14-
14+
/read/project
Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
.. _php-specify-documents-to-return:
2+
3+
===========================
4+
Specify Documents to Return
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, paginate, pagination, order, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to specify which documents and which types to return
24+
from a read operation by passing the following options to the ``MongoDB\Collection::find()``
25+
or ``MongoDB\Collection::findOne()`` method:
26+
27+
- :ref:`limit <php-return-documents-limit>`: Specifies the maximum number of documents
28+
to return from a query
29+
- :ref:`sort <php-return-documents-sort>`: Specifies the sort order for the returned documents
30+
- :ref:`skip <php-return-documents-skip>`: Specifies the number of documents to skip before
31+
returning query results
32+
- :ref:`typeMap <php-return-documents-type>`: Converts the returned documents to a specified data
33+
type
34+
35+
Sample Data
36+
~~~~~~~~~~~
37+
38+
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
39+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
40+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
41+
and assign the following value to your ``collection`` variable:
42+
43+
.. literalinclude:: /includes/read/limit-skip-sort.php
44+
:language: php
45+
:dedent:
46+
:start-after: start-db-coll
47+
:end-before: end-db-coll
48+
49+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
50+
:atlas:`Get Started with Atlas </getting-started>` guide.
51+
52+
.. _php-return-documents-limit:
53+
54+
Limit
55+
-----
56+
57+
To specify the maximum number of documents returned from a read operation, create
58+
an array that sets the ``limit`` option and pass the array as a parameter to the
59+
``MongoDB\Collection::find()`` method.
60+
61+
The following example finds all restaurants that have a ``cuisine`` field value
62+
of ``'Italian'`` and limits the results to ``5`` documents:
63+
64+
.. io-code-block::
65+
:copyable:
66+
67+
.. input:: /includes/read/limit-skip-sort.php
68+
:start-after: start-limit
69+
:end-before: end-limit
70+
:language: php
71+
:dedent:
72+
73+
.. output::
74+
:visible: false
75+
76+
{"_id":{"$oid":"..."},...,"name":"Isle Of Capri Resturant","restaurant_id":"40364373"}
77+
{"_id":{"$oid":"..."},...,"name":"Marchis Restaurant","restaurant_id":"40364668"}
78+
{"_id":{"$oid":"..."},...,"name":"Crystal Room","restaurant_id":"40365013"}
79+
{"_id":{"$oid":"..."},...,"name":"Forlinis Restaurant","restaurant_id":"40365098"}
80+
{"_id":{"$oid":"..."},...,"name":"Angelo Of Mulberry St.","restaurant_id":"40365293"}
81+
82+
.. tip::
83+
84+
The preceding example returns the first five documents matched by the query
85+
according to their :manual:`natural order </reference/glossary/#std-term-natural-order>`
86+
in the database. The following section describes how to return the documents
87+
in a specified order.
88+
89+
.. _php-return-documents-sort:
90+
91+
Sort
92+
----
93+
94+
To return documents in a specified order, create an array that sets the ``sort``
95+
option. When setting this option, include the field to sort the results by and
96+
the sort direction. A value of ``1`` sorts values from lowest to highest, and
97+
a value of ``-1`` sorts them from highest to lowest. Then, pass the array as a
98+
parameter to the ``MongoDB\Collection::find()`` or ``MongoDB\Collection::findOne()``
99+
method.
100+
101+
The following example returns all documents that have a ``cuisine`` value of ``'Italian'``,
102+
sorted in ascending order of ``name`` field values:
103+
104+
.. io-code-block::
105+
:copyable:
106+
107+
.. input:: /includes/read/limit-skip-sort.php
108+
:start-after: start-sort
109+
:end-before: end-sort
110+
:language: php
111+
:dedent:
112+
113+
.. output::
114+
:visible: false
115+
116+
{"_id":{"$oid":"..."},...,"name":"44 Sw Ristorante & Bar","restaurant_id":"40698807"}
117+
{"_id":{"$oid":"..."},...,"name":"900 Park","restaurant_id":"41707964"}
118+
{"_id":{"$oid":"..."},...,"name":"A Voce","restaurant_id":"41434084"}
119+
...
120+
{"_id":{"$oid":"..."},...,"name":"Zucchero E Pomodori","restaurant_id":"41189590" }
121+
122+
.. _php-return-documents-skip:
123+
124+
Skip
125+
----
126+
127+
To skip a specified number of documents before returning your query results, create
128+
an array that sets the ``skip`` option and pass the array as a parameter to the
129+
``MongoDB\Collection::find()`` or ``MongoDB\Collection::findOne()`` method.
130+
131+
The following example returns all documents that have a ``borough`` field value
132+
of ``'Manhattan'`` and skips the first ``10`` documents:
133+
134+
.. io-code-block::
135+
:copyable:
136+
137+
.. input:: /includes/read/limit-skip-sort.php
138+
:start-after: start-skip
139+
:end-before: end-skip
140+
:language: php
141+
:dedent:
142+
143+
.. output::
144+
:visible: false
145+
146+
{"_id":{"$oid":"..."},...,"name":"Cafe Metro","restaurant_id":"40363298"}
147+
{"_id":{"$oid":"..."},...,"name":"Lexler Deli","restaurant_id":"40363426"}
148+
{"_id":{"$oid":"..."},...,"name":"Domino'S Pizza","restaurant_id":"40363644"}
149+
...
150+
151+
.. _php-return-documents-combine:
152+
153+
Combine Limit, Sort, and Skip
154+
-----------------------------
155+
156+
You can set the ``limit``, ``sort``, and ``skip`` options in a single
157+
options array and pass the array as a parameter to the read operation.
158+
This allows you to set a maximum number of sorted documents to return,
159+
skipping a specified number of documents before returning.
160+
161+
The following example returns ``5`` documents that have a ``cuisine`` value of
162+
``'Italian'``. The results are sorted in ascending order by ``name`` field value,
163+
skipping the first ``10`` documents:
164+
165+
.. io-code-block::
166+
:copyable:
167+
168+
.. input:: /includes/read/limit-skip-sort.php
169+
:start-after: start-limit-sort-skip
170+
:end-before: end-limit-sort-skip
171+
:language: php
172+
:dedent:
173+
174+
.. output::
175+
:visible: false
176+
177+
{"_id":{"$oid":"..."},...,"name":"Acqua","restaurant_id":"40871070"}
178+
{"_id":{"$oid":"..."},...,"name":"Acqua Restaurant","restaurant_id":"41591488"}
179+
{"_id":{"$oid":"..."},...,"name":"Acqua Santa","restaurant_id":"40735858"}
180+
{"_id":{"$oid":"..."},...,"name":"Acquista Trattoria","restaurant_id":"40813992"}
181+
{"_id":{"$oid":"..."},...,"name":"Acquolina Catering","restaurant_id":"41381423"}
182+
183+
.. note::
184+
185+
The order in which you call these methods doesn't change the documents
186+
that are returned. The {+php-library+} automatically reorders the calls to
187+
perform the sort operation first, the skip operation next, and then the limit
188+
operation.
189+
190+
.. _php-return-documents-type:
191+
192+
Specify Return Type
193+
-------------------
194+
195+
To customize the data type of documents returned by a read operation, you can pass the
196+
``typeMap`` option in an array parameter.
197+
198+
By default, methods called on a ``MongoDB\Client``, ``MongoDB\Database``, or ``MongoDB\Collection``
199+
instance use the following type map:
200+
201+
.. code-block:: php
202+
203+
[
204+
'array' => 'MongoDB\Model\BSONArray',
205+
'document' => 'MongoDB\Model\BSONDocument',
206+
'root' => 'MongoDB\Model\BSONDocument',
207+
]
208+
209+
This default type map performs the following conversions:
210+
211+
- Arrays to ``MongoDB\Model\BSONArray`` objects
212+
- Top-level and embedded BSON documents to ``MongoDB\Model\BSONDocument`` objects
213+
214+
In a custom type map, you can specify conversions to any type that implements
215+
``MongoDB\BSON\Unserializable``, as well as the ``array``, ``stdClass``, and ``object``
216+
types.
217+
218+
Example
219+
~~~~~~~
220+
221+
The following example returns all documents that have a ``cuisine`` value of ``'Hawaiian'``
222+
and specifies the ``typeMap`` option to convert the documents to array values:
223+
224+
.. io-code-block::
225+
:copyable:
226+
227+
.. input:: /includes/read/limit-skip-sort.php
228+
:start-after: start-return-type
229+
:end-before: end-return-type
230+
:language: php
231+
:dedent:
232+
233+
.. output::
234+
:visible: false
235+
236+
Array
237+
(
238+
[_id] => MongoDB\BSON\ObjectId Object
239+
(
240+
[oid] => ...
241+
)
242+
243+
[address] => Array
244+
(
245+
...
246+
)
247+
248+
[borough] => Manhattan
249+
[cuisine] => Hawaiian
250+
[grades] => Array
251+
(
252+
...
253+
254+
)
255+
256+
[name] => Makana
257+
[restaurant_id] => 41509012
258+
)
259+
...
260+
261+
Additional Information
262+
----------------------
263+
264+
For more information about retrieving documents, see the :ref:`php-retrieve` guide.
265+
266+
For more information about specifying a query, see the :ref:`php-specify-query` guide.
267+
268+
API Documentation
269+
~~~~~~~~~~~~~~~~~
270+
271+
To learn more about any of the methods or types discussed in this
272+
guide, see the following API documentation:
273+
274+
- `MongoDB\\Collection::findOne() <{+api+}/method/MongoDBCollection-findOne/>`__
275+
- `MongoDB\\Collection::find() <{+api+}/method/MongoDBCollection-find/>`__

0 commit comments

Comments
 (0)