Skip to content

Commit 3694bb5

Browse files
committed
DOCSP-41978: Count documents
1 parent e994533 commit 3694bb5

File tree

3 files changed

+284
-1
lines changed

3 files changed

+284
-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+
$db = $client->sample_training;
11+
$collection = $db->companies;
12+
// end-db-coll
13+
14+
// Counts all documents in the collection
15+
// start-count-all
16+
$result = $collection->countDocuments([]);
17+
echo "Number of documents: " . $result;
18+
// end-count-all
19+
20+
// Counts documents that have a "founded_year" value of 2010
21+
// start-count-accurate
22+
$result = $collection->countDocuments(['founded_year' => 2010]);
23+
echo "Number of companies founded in 2010: " . $result;
24+
// end-count-accurate
25+
26+
// Counts a maximum of 100 documents that have a "number_of_employees" value of 50
27+
// start-modify-accurate
28+
$options = ['limit' => 100];
29+
$result = $collection->countDocuments(['number_of_employees' => 50], $options);
30+
echo "Number of companies with 50 employees: " . $result;
31+
// end-modify-accurate
32+
33+
// Estimates the number of documents in the collection
34+
// start-count-estimate
35+
$result = $collection->estimatedDocumentCount();
36+
echo "Estimated number of documents: " . $result;
37+
// end-count-estimate
38+
39+
// Estimates the number of documents in the collection and sets a time limit on the operation
40+
// start-modify-estimate
41+
$options = ['maxTimeMS' => 1000];
42+
$result = $collection->estimatedDocumentCount($options);
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
@@ -8,4 +8,5 @@ Read Data from MongoDB
88
:titlesonly:
99
:maxdepth: 1
1010

11-
/read/retrieve
11+
/read/retrieve
12+
/read/count

source/read/count.txt

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

0 commit comments

Comments
 (0)