Skip to content

Commit 09c7be4

Browse files
authored
DOCSP-41978: Count documents (#108)
* DOCSP-41978: Count documents * edits * code ex format * link * RR feedback
1 parent bdd0fca commit 09c7be4

File tree

3 files changed

+298
-1
lines changed

3 files changed

+298
-1
lines changed

source/includes/read/count.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
require 'vendor/autoload.php';
3+
4+
use MongoDB\BSON\Document;
5+
6+
$uri = getenv('MONGODB_URI') ?: throw new RuntimeException('Set the MONGODB_URI variable to your Atlas URI that connects to the sample dataset');
7+
$client = new MongoDB\Client($uri);
8+
9+
// start-db-coll
10+
$collection = $client->sample_training->companies;
11+
// end-db-coll
12+
13+
// Counts all documents in the collection
14+
// start-count-all
15+
$result = $collection->countDocuments([]);
16+
echo "Number of documents: " . $result;
17+
// end-count-all
18+
19+
// Counts documents that have a "founded_year" value of 2010
20+
// start-count-accurate
21+
$result = $collection->countDocuments(['founded_year' => 2010]);
22+
echo "Number of companies founded in 2010: " . $result;
23+
// end-count-accurate
24+
25+
// Counts a maximum of 100 documents that have a "number_of_employees" value of 50
26+
// start-modify-accurate
27+
$result = $collection->countDocuments(
28+
['number_of_employees' => 50],
29+
['limit' => 100]
30+
);
31+
echo "Number of companies with 50 employees: " . $result;
32+
// end-modify-accurate
33+
34+
// Estimates the number of documents in the collection
35+
// start-count-estimate
36+
$result = $collection->estimatedDocumentCount();
37+
echo "Estimated number of documents: " . $result;
38+
// end-count-estimate
39+
40+
// Estimates the number of documents in the collection and sets a time limit on the operation
41+
// start-modify-estimate
42+
$result = $collection->estimatedDocumentCount(['maxTimeMS' => 1000]);
43+
echo "Estimated number of documents: " . $result;
44+
// end-modify-estimate

source/read.txt

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

1111
/read/retrieve
12+
/read/project
13+
/read/count
1214
/read/specify-documents-to-return
1315
/read/specify-a-query
14-
/read/project

source/read/count.txt

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
.. _php-count:
2+
3+
===============
4+
Count Documents
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: number, amount, estimation, code example
19+
20+
Overview
21+
---------
22+
23+
In this guide, you can learn how to use the {+php-library+} to retrieve an accurate
24+
and estimated count of the number of documents in a collection. The following methods
25+
count documents in a collection:
26+
27+
- ``MongoDB\Collection::countDocuments()``: Returns the exact number of documents that
28+
match a query filter or that exist in a collection
29+
30+
- ``MongoDB\Collection::estimatedDocumentCount()``: Returns the estimated number of documents
31+
in a collection
32+
33+
Sample Data
34+
~~~~~~~~~~~
35+
36+
The examples in this guide use the ``companies`` collection in the ``sample_training``
37+
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
38+
from your PHP application, instantiate a ``MongoDB\Client`` that connects to an Atlas cluster
39+
and assign the following value to your ``collection`` variable:
40+
41+
.. literalinclude:: /includes/read/count.php
42+
:language: php
43+
:dedent:
44+
:start-after: start-db-coll
45+
:end-before: end-db-coll
46+
47+
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
48+
:atlas:`Get Started with Atlas </getting-started>` guide.
49+
50+
.. _php-accurate-count:
51+
52+
Retrieve an Accurate Count
53+
--------------------------
54+
55+
Use the ``MongoDB\Collection::countDocuments()`` method to count the number of documents
56+
in a collection. To count the number of documents that match specific search criteria,
57+
pass a query filter to the ``countDocuments()`` method.
58+
59+
To learn more about specifying a query, see the :ref:`php-specify-query` guide.
60+
61+
Count All Documents
62+
~~~~~~~~~~~~~~~~~~~
63+
64+
To return a count of all documents in the collection, pass an empty query filter array to
65+
the ``countDocuments()`` method, as shown in the following example:
66+
67+
.. io-code-block::
68+
:copyable:
69+
70+
.. input:: /includes/read/count.php
71+
:start-after: start-count-all
72+
:end-before: end-count-all
73+
:language: php
74+
:dedent:
75+
76+
.. output::
77+
:visible: false
78+
79+
Number of documents: 9500
80+
81+
Count Specific Documents
82+
~~~~~~~~~~~~~~~~~~~~~~~~
83+
84+
To return a count of documents that match specific search criteria, pass a query
85+
filter to the ``countDocuments()`` method.
86+
87+
The following example counts the number of documents in which the value of the
88+
``founded_year`` field is ``2010``:
89+
90+
.. io-code-block::
91+
:copyable:
92+
93+
.. input:: /includes/read/count.php
94+
:start-after: start-count-accurate
95+
:end-before: end-count-accurate
96+
:language: php
97+
:dedent:
98+
99+
.. output::
100+
:visible: false
101+
102+
Number of companies founded in 2010: 33
103+
104+
Customize Count Behavior
105+
~~~~~~~~~~~~~~~~~~~~~~~~
106+
107+
You can modify the behavior of the ``countDocuments()`` method by
108+
passing an array that specifies option values. The following table
109+
describes some options you can set to customize the count 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+
* - ``hint``
123+
- | The index to use for the operation.
124+
| **Type**: ``string|array|object``
125+
126+
* - ``comment``
127+
- | The comment to attach to the operation.
128+
| **Type**: any valid BSON type
129+
130+
* - ``limit``
131+
- | The maximum number of documents to count. This value must be a positive integer.
132+
| **Type**: ``integer``
133+
134+
* - ``maxTimeMS``
135+
- | The maximum amount of time in milliseconds that the operation can run.
136+
| **Type**: ``integer``
137+
138+
* - ``skip``
139+
- | The number of documents to skip before counting documents.
140+
| **Type**: ``integer``
141+
142+
* - ``readPreference``
143+
- | The read preference to use for the operation. To learn more, see
144+
:manual:`Read Preference </core/read-preference/>` in the Server manual.
145+
| **Type**: ``MongoDB\Driver\ReadPreference``
146+
147+
The following example uses the ``countDocuments()`` method to count the number of
148+
documents in which the ``number_of_employees`` field has the value ``50`` and instructs the
149+
operation to count a maximum of ``100`` results:
150+
151+
.. io-code-block::
152+
:copyable:
153+
154+
.. input:: /includes/read/count.php
155+
:start-after: start-modify-accurate
156+
:end-before: end-modify-accurate
157+
:language: php
158+
:dedent:
159+
160+
.. output::
161+
:visible: false
162+
163+
Number of companies with 50 employees: 100
164+
165+
.. _php-estimated-count:
166+
167+
Retrieve an Estimated Count
168+
---------------------------
169+
170+
You can retrieve an estimate of the number of documents in a collection by calling
171+
the ``MongoDB\Collection::estimatedDocumentCount()`` method. The method estimates
172+
the amount of documents based on collection metadata, which might be faster than
173+
performing an accurate count.
174+
175+
The following example estimates the number of documents in a collection:
176+
177+
.. io-code-block::
178+
:copyable:
179+
180+
.. input:: /includes/read/count.php
181+
:start-after: start-count-estimate
182+
:end-before: end-count-estimate
183+
:language: php
184+
:dedent:
185+
186+
.. output::
187+
:visible: false
188+
189+
Estimated number of documents: 9500
190+
191+
Customize Estimated Count Behavior
192+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
193+
194+
You can modify the behavior of the ``estimatedDocumentCount()`` method
195+
by passing an array that specifies option values as a parameter. The
196+
following table describes the options you can set in the array:
197+
198+
.. list-table::
199+
:widths: 30 70
200+
:header-rows: 1
201+
202+
* - Option
203+
- Description
204+
205+
* - ``comment``
206+
- | The comment to attach to the operation.
207+
| **Type**: any valid BSON type
208+
209+
* - ``maxTimeMS``
210+
- | The maximum amount of time in milliseconds that the operation can run.
211+
| **Type**: ``integer``
212+
213+
* - ``readConcern``
214+
- | The read concern to use for the operation. To learn more, see
215+
:manual:`Read Concern </reference/read-concern/>` in the Server manual.
216+
| **Type**: ``MongoDB\Driver\ReadConcern``
217+
218+
* - ``readPreference``
219+
- | The read preference to use for the operation. To learn more, see
220+
:manual:`Read Preference </core/read-preference/>` in the Server manual.
221+
| **Type**: ``MongoDB\Driver\ReadPreference``
222+
223+
* - ``session``
224+
- | The client session to associate with the operation.
225+
| **Type**: ``MongoDB\Driver\Session``
226+
227+
The following example uses the ``estimatedDocumentCount()`` method to return an
228+
estimate of the number of documents in the collection and sets a timeout of
229+
``1000`` milliseconds on the operation:
230+
231+
.. io-code-block::
232+
:copyable:
233+
234+
.. input:: /includes/read/count.php
235+
:start-after: start-modify-estimate
236+
:end-before: end-modify-estimate
237+
:language: php
238+
:dedent:
239+
240+
.. output::
241+
:visible: false
242+
243+
Estimated number of documents: 9500
244+
245+
API Documentation
246+
-----------------
247+
248+
To learn more about any of the methods or types discussed in this
249+
guide, see the following API documentation:
250+
251+
- `MongoDB\\Collection::countDocuments() <{+api+}/method/MongoDBCollection-countDocuments/>`__
252+
- `MongoDB\\Collection::estimatedDocumentCount() <{+api+}/method/MongoDBCollection-estimatedDocumentCount/>`__

0 commit comments

Comments
 (0)