File tree Expand file tree Collapse file tree 1 file changed +18
-3
lines changed
source/fundamentals/crud/read-operations Expand file tree Collapse file tree 1 file changed +18
-3
lines changed Original file line number Diff line number Diff line change @@ -51,12 +51,27 @@ Accurate Count
5151--------------
5252
5353To 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
6176Modify Behavior
6277~~~~~~~~~~~~~~~
You can’t perform that action at this time.
0 commit comments