Skip to content

Commit 2122c5a

Browse files
DOCSP-27256 Add note for collScan workaround (#350)
1 parent 1dc7fc8 commit 2122c5a

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

source/usage-examples/count.txt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ than scanning the entire collection. The ``countDocuments()`` method returns
2323
an **accurate** count of the number of documents and supports specifying
2424
a filter.
2525

26+
.. tip::
27+
28+
When using ``countDocuments()`` to return the total number of documents in a
29+
collection, you can improve performance by avoiding a collection scan. To do
30+
this, use a :manual:`hint </reference/method/cursor.hint>` to take advantage
31+
of the built-in index on the ``_id`` field. Use this technique only when
32+
calling ``countDocuments()`` with an empty query parameter.
33+
34+
.. code-block:: java
35+
36+
CountOptions opts = new CountOptions().hintString("_id_");
37+
long numDocuments = collection.countDocuments(new BsonDocument(), opts);
38+
2639
When you call the ``countDocuments()`` method, you can optionally pass a
2740
**query filter** parameter. You cannot pass any parameters when you call
2841
``estimatedDocumentCount()``.

0 commit comments

Comments
 (0)