Skip to content

Commit 12d9f71

Browse files
DOCSP-13836 crud limit (#63)
* added CRUD Limit page
1 parent d30a55c commit 12d9f71

File tree

6 files changed

+253
-16
lines changed

6 files changed

+253
-16
lines changed

source/fundamentals/crud/read-operations.txt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@ Read Operations
77
- :doc:`/fundamentals/crud/read-operations/retrieve`
88
- :doc:`/fundamentals/crud/read-operations/sort`
99
- :doc:`/fundamentals/crud/read-operations/skip`
10+
- :doc:`/fundamentals/crud/read-operations/limit`
1011

1112
..
1213
- :doc:`/fundamentals/crud/read-operations/cursor`
13-
- :doc:`/fundamentals/crud/read-operations/limit`
1414
- :doc:`/fundamentals/crud/read-operations/project`
1515
- :doc:`/fundamentals/crud/read-operations/geo`
1616
- :doc:`/fundamentals/crud/read-operations/text`
@@ -21,9 +21,9 @@ Read Operations
2121
/fundamentals/crud/read-operations/retrieve
2222
/fundamentals/crud/read-operations/sort
2323
/fundamentals/crud/read-operations/skip
24+
/fundamentals/crud/read-operations/limit
2425
..
2526
/fundamentals/crud/read-operations/cursor
26-
/fundamentals/crud/read-operations/limit
2727
/fundamentals/crud/read-operations/project
2828
/fundamentals/crud/read-operations/geo
2929
/fundamentals/crud/read-operations/text

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

Lines changed: 149 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,152 @@ Limit the Number of Returned Results
44

55
.. default-domain:: mongodb
66

7-
Use ``limit()`` to cap the number of documents that a read operation returns.
8-
This instance method designates the maximum number of
9-
documents that a read operation can return. If there are not enough documents
10-
to reach the specified limit, it can return a smaller number.
11-
If you use ``limit()`` with the ``skip()`` (TODO: link) instance method, the skip applies
12-
first and the limit only applies to the documents left over after
13-
the skip.
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
Overview
14+
--------
15+
16+
In this guide, you can learn how to limit the number of documents
17+
returned from a read operation.
18+
19+
Sample Data
20+
~~~~~~~~~~~
21+
22+
Run the following snippet to load the documents into the ``ratings``
23+
collection of the ``tea`` database:
24+
25+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
26+
:language: go
27+
:dedent:
28+
:start-after: begin insertDocs
29+
:end-before: end insertDocs
30+
31+
.. include:: /includes/fundamentals/tea-sample-data-ending.rst
32+
33+
Limit
34+
-----
35+
36+
To limit the number of documents returned from a query, pass the
37+
number of documents you want returned to the ``SetLimit()`` function of
38+
the read operation's options.
39+
40+
Specify the options as the last parameter to the following read
41+
operation functions:
42+
43+
- ``Find()``
44+
- ``CountDocuments()``
45+
- ``gridfs.Bucket.Find()``
46+
47+
If the limit is ``0`` or exceeds the number of matched
48+
documents, the function returns all the documents. If the limit is a
49+
negative number, the function behaves as if the limit was the absolute
50+
value of the negative number and closes the cursor after retrieving
51+
documents.
52+
53+
Example
54+
~~~~~~~
55+
56+
The following example shows how to return two documents:
57+
58+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
59+
:language: go
60+
:dedent:
61+
:start-after: begin limit
62+
:end-before: end limit
63+
64+
After running the preceding example, the output resembles the following:
65+
66+
.. code-block:: none
67+
:copyable: false
68+
69+
//results truncated
70+
[{_id ObjectID("...")} {type Masala} {rating 10}]
71+
[{_id ObjectID("...")} {type Assam} {rating 5}]
72+
73+
.. tip:: Using Aggregation
74+
75+
You can also include the :manual:`$limit </reference/operator/aggregation/limit/>`
76+
stage to specify a limit in an aggregation pipeline.
77+
78+
The following example specifies the same limit from the
79+
preceding example in an aggregation pipeline:
80+
81+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
82+
:language: go
83+
:dedent:
84+
:start-after: begin aggregate limit
85+
:end-before: end aggregate limit
86+
87+
Multiple Options
88+
----------------
89+
90+
If you configure other options alongside the ``SetLimit()`` function,
91+
the driver performs the limit last regardless of the order you list
92+
the options.
93+
94+
Example
95+
~~~~~~~
96+
97+
The following example performs the following actions in order using the
98+
``Find()`` function:
99+
100+
- Sort the ``rating`` field in descending order
101+
- Skip the first document
102+
- Return the first two of the remaining documents
103+
104+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
105+
:language: go
106+
:dedent:
107+
:start-after: begin multi options
108+
:end-before: end multi options
109+
110+
After running the preceding example, the output resembles the following:
111+
112+
.. code-block:: none
113+
:copyable: false
114+
115+
//results truncated
116+
[{_id ObjectID("...")} {type Earl Grey} {rating 8}]
117+
[{_id ObjectID("...")} {type Oolong} {rating 7}]
118+
119+
.. tip::
120+
121+
Using any of the following option declarations also produce the same result:
122+
123+
.. code-block:: go
124+
:copyable: false
125+
126+
multiOptions := options.Find().SetSort(bson.D{{"rating", -1}}).SetSkip(1).SetLimit(2)
127+
multiOptions := options.Find().SetLimit(2).SetSort(bson.D{{"rating", -1}}).SetSkip(1)
128+
multiOptions := options.Find().SetLimit(2).SetSkip(1).SetSort(bson.D{{"rating", -1}})
129+
multiOptions := options.Find().SetSkip(1).SetSort(bson.D{{"rating", -1}}).SetLimit(2)
130+
multiOptions := options.Find().SetSkip(1).SetLimit(2).SetSort(bson.D{{"rating", -1}})
131+
132+
Additional Information
133+
----------------------
134+
135+
For more information on performing read operations, see our guide on
136+
:doc:`retrieving data </fundamentals/crud/read-operations/retrieve>`.
137+
138+
For information on specifying a sort, see our guide on :doc:`sorting
139+
results </fundamentals/crud/read-operations/sort>`.
140+
141+
.. For information on skipping results, see our guide on :doc:`skipping
142+
.. returned results </fundamentals/crud/read-operations/skip>`.
143+
144+
API Documentation
145+
~~~~~~~~~~~~~~~~~
146+
147+
For more information on any of the functions or types discussed in this
148+
guide, see the following API Documentation:
149+
150+
- `FindOptions.SetLimit() <{+api+}/mongo/options#FindOptions.SetLimit>`__
151+
- `FindOptions.SetSort() <{+api+}/mongo/options#FindOptions.SetSort>`__
152+
- `FindOptions.SetSkip() <{+api+}/mongo/options#FindOptions.SetSkip>`__
153+
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__
154+
- `CountDocuments() <{+api+}/mongo#Collection.CountDocuments>`__
155+
- `gridfs.Bucket.Find() <{+api+}/mongo/gridfs#Bucket.Find>`__

source/includes/fundamentals/code-snippets/CRUD/delete.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ func main() {
4343
if insertErr != nil {
4444
panic(insertErr)
4545
}
46-
// end insertDocs
4746
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
47+
// end insertDocs
4848

4949
// begin deleteMany
5050
deleteManyFilter := bson.D{{"rating", bson.D{{"$gt", 8}}}}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
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+
22+
if err != nil {
23+
panic(err)
24+
}
25+
defer func() {
26+
if err = client.Disconnect(context.TODO()); err != nil {
27+
panic(err)
28+
}
29+
}()
30+
31+
client.Database("tea").Collection("ratings").Drop(context.TODO())
32+
33+
// begin insertDocs
34+
coll := client.Database("tea").Collection("ratings")
35+
docs := []interface{}{
36+
bson.D{{"type", "Masala"}, {"rating", 10}},
37+
bson.D{{"type", "Assam"}, {"rating", 5}},
38+
bson.D{{"type", "Oolong"}, {"rating", 7}},
39+
bson.D{{"type", "Earl Grey"}, {"rating", 8}},
40+
bson.D{{"type", "English Breakfast"}, {"rating", 5}},
41+
}
42+
43+
result, insertErr := coll.InsertMany(context.TODO(), docs)
44+
if insertErr != nil {
45+
panic(insertErr)
46+
}
47+
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
48+
//end insertDocs
49+
50+
fmt.Println("Limit:")
51+
//begin limit
52+
limitFilter := bson.D{}
53+
limitOptions := options.Find().SetLimit(2)
54+
55+
limitCursor, limitErr := coll.Find(context.TODO(), limitFilter, limitOptions)
56+
57+
var limitResults []bson.D
58+
if limitErr = limitCursor.All(context.TODO(), &limitResults); limitErr != nil {
59+
panic(limitErr)
60+
}
61+
for _, result := range limitResults {
62+
fmt.Println(result)
63+
}
64+
//end limit
65+
66+
fmt.Println("Limit, Skip and Sort:")
67+
//begin multi options
68+
multiFilter := bson.D{}
69+
multiOptions := options.Find().SetSort(bson.D{{"rating", -1}}).SetLimit(2).SetSkip(1)
70+
71+
multiCursor, multiErr := coll.Find(context.TODO(), multiFilter, multiOptions)
72+
73+
var multiResults []bson.D
74+
if multiErr = multiCursor.All(context.TODO(), &multiResults); multiErr != nil {
75+
panic(multiErr)
76+
}
77+
for _, result := range multiResults {
78+
fmt.Println(result)
79+
}
80+
//end multi options
81+
82+
fmt.Println("Aggregation Limit:")
83+
// begin aggregate limit
84+
limitStage := bson.D{{"$limit", 2}}
85+
86+
aggCursor, aggErr := coll.Aggregate(context.TODO(), mongo.Pipeline{limitStage})
87+
if aggErr != nil {
88+
panic(aggErr)
89+
}
90+
91+
var aggResults []bson.D
92+
if aggErr = aggCursor.All(context.TODO(), &aggResults); aggErr != nil {
93+
panic(aggErr)
94+
}
95+
for _, result := range aggResults {
96+
fmt.Println(result)
97+
}
98+
// end aggregate limit
99+
}

source/includes/fundamentals/code-snippets/CRUD/retrieve.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,9 @@ func main() {
4141
if err != nil {
4242
panic(err)
4343
}
44+
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
4445
// end insert docs
4546

46-
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
47-
for _, id := range result.InsertedIDs {
48-
fmt.Printf("\t%s\n", id)
49-
}
50-
5147
// begin find docs
5248
filter := bson.D{
5349
{"$and",

source/includes/fundamentals/code-snippets/CRUD/sort.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ func main() {
4444
if insertErr != nil {
4545
panic(insertErr)
4646
}
47-
//end insertDocs
4847
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
48+
//end insertDocs
4949

5050
fmt.Println("Ascending Sort:")
5151
//begin ascending sort

0 commit comments

Comments
 (0)