Skip to content

Commit 6233f4d

Browse files
DOCSP-18236 crud count documents (#72)
* added CRUD Count Documents
1 parent cb77aee commit 6233f4d

File tree

6 files changed

+313
-5
lines changed

6 files changed

+313
-5
lines changed

source/fundamentals/crud/compound-operations.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,9 @@ following guides:
317317
API Documentation
318318
~~~~~~~~~~~~~~~~~
319319

320+
For more information on any of the functions or types discussed in this
321+
guide, see the following API Documentation:
322+
320323
- `FindOneAndDelete() <{+api+}/mongo#Collection.FindOneAndDelete>`__
321324
- `FindOneAndDeleteOptions <{+api+}/mongo/options#FindOneAndDeleteOptions>`__
322325
- `FindOneAndUpdate() <{+api+}/mongo#Collection.FindOneAndUpdate>`__

source/fundamentals/crud/read-operations.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Read Operations
44

55
.. default-domain:: mongodb
66

7+
- :doc:`/fundamentals/crud/read-operations/count`
78
- :doc:`/fundamentals/crud/read-operations/retrieve`
89
- :doc:`/fundamentals/crud/read-operations/sort`
910
- :doc:`/fundamentals/crud/read-operations/skip`
@@ -18,6 +19,7 @@ Read Operations
1819
.. toctree::
1920
:caption: Read Operations
2021

22+
/fundamentals/crud/read-operations/count
2123
/fundamentals/crud/read-operations/retrieve
2224
/fundamentals/crud/read-operations/sort
2325
/fundamentals/crud/read-operations/skip
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
===============
2+
Count Documents
3+
===============
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 1
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to get an :ref:`accurate
17+
<accurate-count-go>` and :ref:`estimated <estimated-count-go>` count of
18+
the number of documents in your collection.
19+
20+
Sample Data
21+
~~~~~~~~~~~
22+
23+
To run the example in this guide, load the sample data into the
24+
``ratings`` collection of the ``tea`` database with the following
25+
snippet:
26+
27+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/countAndEstimate.go
28+
:language: go
29+
:dedent:
30+
:start-after: begin insert docs
31+
:end-before: end insert docs
32+
33+
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
34+
35+
Each document contains a rating for a type of tea that corresponds to
36+
the ``type`` and ``rating`` fields.
37+
38+
.. _accurate-count-go:
39+
40+
Accurate Count
41+
--------------
42+
43+
To count the number of documents that match your query filter, use the
44+
``CountDocuments()`` function.
45+
46+
.. tip::
47+
48+
If you pass an empty query filter, this function returns the total
49+
number of documents in the collection.
50+
51+
Modify Behavior
52+
~~~~~~~~~~~~~~~
53+
54+
You can modify the behavior of ``CountDocuments()`` by passing in a
55+
``CountOptions`` type. If you don't specify any options, the driver uses
56+
its default values.
57+
58+
The ``CountOptions`` type allows you to configure options with the
59+
following functions:
60+
61+
.. list-table::
62+
:widths: 30 70
63+
:header-rows: 1
64+
65+
* - Function
66+
- Description
67+
68+
* - ``SetCollation()``
69+
- | The type of language collation to use when sorting results.
70+
| Default: ``nil``
71+
72+
* - ``SetHint()``
73+
- | The index to use to scan for documents to count.
74+
| Default: ``nil``
75+
76+
* - ``SetLimit()``
77+
- | The maximum number of documents to count.
78+
| Default: ``0``
79+
80+
* - ``SetMaxTime()``
81+
- | The maximum amount of time that the query can run on the server.
82+
| Default: ``nil``
83+
84+
* - ``SetSkip()``
85+
- | The number of documents to skip before counting.
86+
| Default: ``0``
87+
88+
Example
89+
```````
90+
91+
The following example counts the number of documents where the
92+
``rating`` is less than ``6``:
93+
94+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/countAndEstimate.go
95+
:language: go
96+
:dedent:
97+
:start-after: begin count documents
98+
:end-before: end count documents
99+
100+
After running this example, the output resembles the following:
101+
102+
.. code-block:: none
103+
:copyable: false
104+
105+
Number of ratings less than six: 4
106+
107+
Aggregation
108+
-----------
109+
110+
You can also include the :manual:`$count </reference/operator/aggregation/count/>`
111+
stage to count the number of documents in an aggregation pipeline.
112+
113+
Example
114+
~~~~~~~
115+
116+
The following example performs the following actions:
117+
118+
- Counts the number of documents where the ``rating`` is greater than ``5``
119+
- Assigns the count to a field called ``total_documents``
120+
121+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/countAndEstimate.go
122+
:language: go
123+
:dedent:
124+
:start-after: begin aggregate count
125+
:end-before: end aggregate count
126+
127+
After running this example, the output resembles the following:
128+
129+
.. code-block:: none
130+
:copyable: false
131+
132+
[{total_documents 5}]
133+
134+
.. _estimated-count-go:
135+
136+
Estimated Count
137+
---------------
138+
139+
To estimate the number of documents in your collection, use the
140+
``EstimatedDocumentCount()`` function.
141+
142+
.. note::
143+
144+
The ``EstimatedDocumentCount()`` function is quicker than the
145+
``CountDocuments()`` function because it uses the collection's
146+
metadata rather than scanning the entire collection.
147+
148+
Modify Behavior
149+
~~~~~~~~~~~~~~~
150+
151+
You can modify the behavior of ``EstimatedDocumentCount()`` by passing
152+
in an ``EstimatedDocumentCountOptions`` type. If you don't specify any
153+
options, the driver uses its default values.
154+
155+
The ``EstimatedDocumentCountOptions`` type allows you to configure
156+
options with the following functions:
157+
158+
.. list-table::
159+
:widths: 30 70
160+
:header-rows: 1
161+
162+
* - Function
163+
- Description
164+
165+
* - ``SetMaxTime()``
166+
- | The maximum amount of time that the query can run on the server.
167+
| Default: ``nil``
168+
169+
Example
170+
```````
171+
172+
The following example estimates the number of documents in the
173+
``ratings`` collection:
174+
175+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/countAndEstimate.go
176+
:language: go
177+
:dedent:
178+
:start-after: begin est doc count
179+
:end-before: end est doc count
180+
181+
After running this example, the output resembles the following:
182+
183+
.. code-block:: none
184+
:copyable: false
185+
186+
Estimated number of documents in the ratings collection: 9
187+
188+
Additional Information
189+
----------------------
190+
191+
For more information on the operations mentioned, see the following
192+
guides:
193+
194+
- :doc:`Specify a Query </fundamentals/crud/query-document>`
195+
- :doc:`Skip Returned Results </fundamentals/crud/read-operations/skip>`
196+
- :doc:`Limit the Number of Returned Results </fundamentals/crud/read-operations/limit>`
197+
198+
.. - :doc:`Aggregation </fundamentals/aggregation>`
199+
.. - :doc:`Collations </fundamentals/collations>`
200+
201+
API Documentation
202+
~~~~~~~~~~~~~~~~~
203+
204+
For more information on any of the functions or types discussed in this
205+
guide, see the following API Documentation:
206+
207+
- `CountDocuments() <{+api+}/mongo#Collection.CountDocuments>`__
208+
- `CountOptions <{+api+}/mongo/options#CountOptions>`__
209+
- `EstimatedDocumentCount() <{+api+}/mongo#Collection.EstimatedDocumentCount>`__
210+
- `EstimatedDocumentCountOptions <{+api+}/mongo/options#EstimatedDocumentCountOptions>`__

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,11 +212,11 @@ following functions:
212212
| Default: ``nil``
213213

214214
* - ``SetMaxTime()``
215-
- | The maximum amount of time in milliseconds to allow the query to run.
215+
- | The maximum amount of time to allow the query to run.
216216
| Default: ``nil``
217217

218218
* - ``SetMaxAwaitTime()``
219-
- | The maximum amount of time in milliseconds for the server to wait on new documents to satisfy a tailable cursor query.
219+
- | The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
220220
| Default: ``nil``
221221

222222
* - ``SetComment()``
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"os"
8+
9+
"go.mongodb.org/mongo-driver/bson"
10+
"go.mongodb.org/mongo-driver/mongo"
11+
"go.mongodb.org/mongo-driver/mongo/options"
12+
)
13+
14+
func main() {
15+
var uri string
16+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
17+
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
18+
}
19+
20+
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
21+
if err != nil {
22+
panic(err)
23+
}
24+
defer func() {
25+
if err = client.Disconnect(context.TODO()); err != nil {
26+
panic(err)
27+
}
28+
}()
29+
30+
client.Database("tea").Collection("ratings").Drop(context.TODO())
31+
32+
// begin insert docs
33+
coll := client.Database("tea").Collection("ratings")
34+
docs := []interface{}{
35+
bson.D{{"type", "Masala"}, {"rating", 10}},
36+
bson.D{{"type", "Matcha"}, {"rating", 7}},
37+
bson.D{{"type", "Assam"}, {"rating", 4}},
38+
bson.D{{"type", "Oolong"}, {"rating", 9}},
39+
bson.D{{"type", "Chrysanthemum"}, {"rating", 5}},
40+
bson.D{{"type", "Earl Grey"}, {"rating", 8}},
41+
bson.D{{"type", "Jasmine"}, {"rating", 3}},
42+
bson.D{{"type", "English Breakfast"}, {"rating", 6}},
43+
bson.D{{"type", "White Peony"}, {"rating", 4}},
44+
}
45+
46+
result, err := coll.InsertMany(context.TODO(), docs)
47+
if err != nil {
48+
panic(err)
49+
}
50+
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
51+
//end insert docs
52+
53+
{
54+
// begin count documents
55+
filter := bson.D{{"rating", bson.D{{"$lt", 6}}}}
56+
57+
count, err := coll.CountDocuments(context.TODO(), filter)
58+
if err != nil {
59+
panic(err)
60+
}
61+
fmt.Printf("Number of ratings less than six: %d\n", count)
62+
// end count documents
63+
}
64+
65+
{
66+
// begin est doc count
67+
count, err := coll.EstimatedDocumentCount(context.TODO())
68+
if err != nil {
69+
panic(err)
70+
}
71+
fmt.Printf("Estimated number of documents in the ratings collection: %d\n", count)
72+
// end est doc count
73+
}
74+
75+
{
76+
// begin aggregate count
77+
matchStage := bson.D{{"$match", bson.D{{"rating", bson.D{{"$gt", 5}}}}}}
78+
countStage := bson.D{{"$count", "total_documents"}}
79+
80+
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, countStage})
81+
if err != nil {
82+
panic(err)
83+
}
84+
85+
var results []bson.D
86+
if err = cursor.All(context.TODO(), &results); err != nil {
87+
panic(err)
88+
}
89+
for _, result := range results {
90+
fmt.Println(result)
91+
}
92+
// end aggregate count
93+
}
94+
}

source/usage-examples/count.txt

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,8 @@ After you run the full example, you should see the following:
4444
Additional Information
4545
----------------------
4646

47-
..
48-
For more information on counting documents, see our guide on
49-
<TODO: Counting Documents>.
47+
For more information on counting documents, see our guide on
48+
:doc:`Counting Documents </fundamentals/crud/read-operations/count>`.
5049

5150
API Documentation
5251
~~~~~~~~~~~~~~~~~

0 commit comments

Comments
 (0)