Skip to content

Commit dae75f0

Browse files
DOCSP-27258 countDocuments collScan note (#245)
1 parent 255b09f commit dae75f0

File tree

1 file changed

+18
-3
lines changed
  • source/fundamentals/crud/read-operations

1 file changed

+18
-3
lines changed

source/fundamentals/crud/read-operations/count.txt

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,27 @@ Accurate Count
5151
--------------
5252

5353
To count the number of documents that match your query filter, use the
54-
``CountDocuments()`` method.
54+
``CountDocuments()`` method. If you pass an empty query filter, this method
55+
returns the total number of documents in the collection.
5556

5657
.. tip::
5758

58-
If you pass an empty query filter, this method returns the total
59-
number of documents in the collection.
59+
When you use ``CountDocuments()`` to return the total number of documents in a
60+
collection, MongoDB performs a collection scan. You can avoid a collection scan and
61+
improve the performance of this method by using a :manual:`hint
62+
</reference/method/cursor.hint>` to take advantage of the built-in index on
63+
the ``_id`` field. Use this technique only when calling ``CountDocuments()``
64+
with an empty query parameter.
65+
66+
.. code-block:: go
67+
:emphasize-lines: 1, 3
68+
69+
opts := options.Count().SetHint("_id_")
70+
71+
count, err := coll.CountDocuments(context.TODO(), bson.D{}, opts)
72+
if err != nil {
73+
panic(err)
74+
}
6075

6176
Modify Behavior
6277
~~~~~~~~~~~~~~~

0 commit comments

Comments
 (0)