|
| 1 | +============================================= |
| 2 | +Count the Number of Documents in a Collection |
| 3 | +============================================= |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +Overview |
| 8 | +-------- |
| 9 | + |
| 10 | +The Node.js driver provides two methods for counting |
| 11 | +documents in a collection: |
| 12 | + |
| 13 | +- :node-api:`collection.countDocuments() |
| 14 | + </Collection.html#countDocuments>` returns the number of documents in |
| 15 | + the collection that match the specified query. If you specify a empty |
| 16 | + query document, ``countDocuments()`` returns the total number of |
| 17 | + documents in the collection. |
| 18 | + |
| 19 | +- :node-api:`collection.estimatedDocumentCount |
| 20 | + </Collection.html#estimatedDocumentCount>` returns an |
| 21 | + **estimation** of the number of documents in the collection based on |
| 22 | + collection metadata. |
| 23 | + |
| 24 | +``estimatedDocumentCount()`` is faster than ``countDocuments()`` because |
| 25 | +the estimation is based on the collection's metadata rather than scanning |
| 26 | +the collection. In contrast, |
| 27 | +``countDocuments()`` takes longer to return, but provides an |
| 28 | +**accurate** count of the number of documents and supports specifying a |
| 29 | +filter. Choose the appropriate method for your workload. |
| 30 | + |
| 31 | +To specify which documents you wish to count, ``countDocuments()`` |
| 32 | +accepts a :manual:`query </tutorial/query-documents>` parameter. |
| 33 | +``countDocuments()`` will only count the documents that match the |
| 34 | +specified query. |
| 35 | + |
| 36 | +``countDocuments()`` and ``estimatedDocumentCount()`` support optional |
| 37 | +settings that affect the method's execution. Refer to the reference |
| 38 | +documentation for each method for more information. |
| 39 | + |
| 40 | +Depending on whether you specify a Callback method, ``countDocuments()`` and ``estimatedDocumentCount()`` behave in two |
| 41 | +different ways: |
| 42 | + |
| 43 | +- If you do not specify a callback method, ``countDocuments()`` and |
| 44 | + ``estimatedDocumentCount()`` return a Promise that resolves to a |
| 45 | + number. |
| 46 | + |
| 47 | +- If you do specify a callback, ``countDocuments()`` and |
| 48 | + ``estimatedDocumentCount`` return a :node-api:`countCallback |
| 49 | + <Collection.html#~countCallback>` object. |
| 50 | + |
| 51 | +Example |
| 52 | +------- |
| 53 | + |
| 54 | +The following example estimates the number of documents in the ``movies`` |
| 55 | +collection in the ``sample_mflix`` database, and then returns an accurate |
| 56 | +count of the number of documents in the ``movies`` collection with |
| 57 | +``Canada`` in the ``countries`` field. |
| 58 | + |
| 59 | +.. literalinclude:: /code-snippets/usage-examples/count.js |
| 60 | + :language: javascript |
0 commit comments