Skip to content

Commit 8c7a538

Browse files
authored
DOCSP-26440: use struct on skip pg (#217)
* DOCSP-26440: use struct in sort pg * small fixes * MW PR fixes 1
1 parent 612db46 commit 8c7a538

File tree

2 files changed

+80
-58
lines changed
  • source
    • fundamentals/crud/read-operations
    • includes/fundamentals/code-snippets/CRUD

2 files changed

+80
-58
lines changed

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

Lines changed: 53 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,17 @@ results from read operations.
2121
Sample Data
2222
~~~~~~~~~~~
2323

24-
To run the example in this guide, load these documents into the
25-
``tea.ratings`` collection with the following
24+
The examples in this guide use the following ``Course`` struct as a model for documents
25+
in the ``courses`` collection:
26+
27+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/skip.go
28+
:start-after: start-course-struct
29+
:end-before: end-course-struct
30+
:language: go
31+
:dedent:
32+
33+
To run the examples in this guide, load these documents into the
34+
``db.courses`` collection with the following
2635
snippet:
2736

2837
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/skip.go
@@ -31,7 +40,11 @@ snippet:
3140
:start-after: begin insertDocs
3241
:end-before: end insertDocs
3342

34-
.. include:: /includes/fundamentals/tea-sample-data-ending.rst
43+
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
44+
45+
Each document contains a description of a university course that
46+
includes the course title and maximum enrollment, corresponding to
47+
the ``title`` and ``enrollment`` fields.
3548

3649
Skip
3750
----
@@ -40,8 +53,7 @@ To skip a specified number of returned results from a query, pass the
4053
number of documents you want to skip to the ``SetSkip()`` method of
4154
the read operation's options.
4255

43-
Specify the options as the last parameter to the following read
44-
operation methods:
56+
The following read operations take an options object as a parameter:
4557

4658
- ``Find()``
4759
- ``FindOne()``
@@ -53,20 +65,21 @@ query, that query returns no documents.
5365

5466
.. tip::
5567

56-
Passing in a negative number to the ``SetSkip()`` method results
57-
in a runtime error.
68+
Passing in a negative number to the ``SetSkip()`` method results
69+
in a runtime error.
5870

59-
Documents return in a natural order, which can lead to skipping random
60-
documents. To avoid this, use a ``SetSort()`` method before the
61-
``SetSkip()`` method.
71+
Find operations return documents in a natural order that is not sorted
72+
on any field. To avoid skipping random documents, use the ``SetSort()``
73+
method to sort documents on a field with unique values before setting a
74+
skip option.
6275

6376
Example
6477
~~~~~~~
6578

66-
The following example performs the following actions in order with the
67-
``Find()`` method:
79+
The following example performs a ``Find()`` operation with the following
80+
behavior:
6881

69-
- An ascedning sort on the ``rating`` field
82+
- Sorts results in ascending order on the ``enrollment`` field
7083
- Skips the first two documents
7184

7285
.. io-code-block::
@@ -75,72 +88,73 @@ The following example performs the following actions in order with the
7588
.. input::
7689
:language: go
7790

78-
filter := bson.D{}
79-
opts := options.Find().SetSort(bson.D{{"rating", 1}}).SetSkip(2)
80-
81-
cursor, err := coll.Find(context.TODO(), filter, opts)
82-
83-
var results []bson.D
91+
opts := options.Find().SetSort(bson.D{{"enrollment", 1}}).SetSkip(2)
92+
93+
cursor, err := coll.Find(context.TODO(), bson.D{}, opts)
94+
95+
var results []Course
8496
if err = cursor.All(context.TODO(), &results); err != nil {
85-
panic(err)
97+
panic(err)
8698
}
8799
for _, result := range results {
88-
fmt.Println(result)
100+
res, _ := json.Marshal(result)
101+
fmt.Println(string(res))
89102
}
90103

91104
.. output::
92105
:language: none
93106
:visible: false
94107

95-
[{_id ObjectID("...")} {type Oolong} {rating 7}]
96-
[{_id ObjectID("...")} {type Earl Grey} {rating 8}]
97-
[{_id ObjectID("...")} {type Masala} {rating 10}]
108+
{"Title":"Plate Tectonics","Enrollment":45}
109+
{"Title":"Abstract Algebra","Enrollment":60}
98110

99111
.. _golang-skip-aggregation:
100112

101113
Aggregation
102114
-----------
103115

104116
You can also include the :manual:`$skip </reference/operator/aggregation/skip/>`
105-
stage to specify a skip in an aggregation pipeline.
117+
stage in an aggregation pipeline to skip documents.
106118

107119
Example
108120
~~~~~~~
109121

110-
The following example performs the following actions in order with the
111-
``Aggregate()`` method:
122+
The following example performs an ``Aggregate()`` operation with the following
123+
behavior:
112124

113-
- A descending sort on the ``rating`` field
114-
- Skips the first three documents
125+
- Sorts results in descending order on the ``enrollment`` field
126+
- Skips the first document
115127

116128
.. io-code-block::
117129
:copyable: true
118130

119131
.. input::
120132
:language: go
121133

122-
sortStage := bson.D{{"$sort", bson.D{{"rating", -1}}}}
123-
skipStage := bson.D{{"$skip", 3}}
124-
134+
sortStage := bson.D{{"$sort", bson.D{{"enrollment", -1}}}}
135+
skipStage := bson.D{{"$skip", 1}}
136+
125137
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage, skipStage})
126138
if err != nil {
127-
panic(err)
139+
panic(err)
128140
}
129-
130-
var results []bson.D
141+
142+
var results []Course
131143
if err = cursor.All(context.TODO(), &results); err != nil {
132-
panic(err)
144+
panic(err)
133145
}
134146
for _, result := range results {
135-
fmt.Println(result)
147+
res, _ := json.Marshal(result)
148+
fmt.Println(string(res))
136149
}
137150

138151
.. output::
139152
:language: none
140153
:visible: false
141154

142-
[{_id ObjectID("...")} {type Assam} {rating 5}]
143-
[{_id ObjectID("...")} {type English Breakfast} {rating 5}]
155+
{"Title":"Plate Tectonics","Enrollment":45}
156+
{"Title":"World Fiction","Enrollment":35}
157+
{"Title":"Modern Poetry","Enrollment":12}
144158

145159
Additional Information
146160
----------------------

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

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"context"
5+
"encoding/json"
56
"fmt"
67
"log"
78
"os"
@@ -11,6 +12,14 @@ import (
1112
"go.mongodb.org/mongo-driver/mongo/options"
1213
)
1314

15+
// start-course-struct
16+
type Course struct {
17+
Title string
18+
Enrollment int32
19+
}
20+
21+
// end-course-struct
22+
1423
func main() {
1524
var uri string
1625
if uri = os.Getenv("MONGODB_URI"); uri == "" {
@@ -28,60 +37,59 @@ func main() {
2837
}
2938
}()
3039

31-
client.Database("tea").Collection("ratings").Drop(context.TODO())
32-
3340
// begin insertDocs
34-
coll := client.Database("tea").Collection("ratings")
41+
coll := client.Database("db").Collection("courses")
3542
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}},
43+
Course{Title: "World Fiction", Enrollment: 35},
44+
Course{Title: "Abstract Algebra", Enrollment: 60},
45+
Course{Title: "Modern Poetry", Enrollment: 12},
46+
Course{Title: "Plate Tectonics", Enrollment: 45},
4147
}
4248

4349
result, err := coll.InsertMany(context.TODO(), docs)
50+
//end insertDocs
51+
4452
if err != nil {
4553
panic(err)
4654
}
4755
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
48-
//end insertDocs
4956

50-
fmt.Println("Skip:")
57+
fmt.Println("\nSkip:\n")
5158
{
5259
//begin skip
53-
filter := bson.D{}
54-
opts := options.Find().SetSort(bson.D{{"rating", 1}}).SetSkip(2)
60+
opts := options.Find().SetSort(bson.D{{"enrollment", 1}}).SetSkip(2)
5561

56-
cursor, err := coll.Find(context.TODO(), filter, opts)
62+
cursor, err := coll.Find(context.TODO(), bson.D{}, opts)
5763

58-
var results []bson.D
64+
var results []Course
5965
if err = cursor.All(context.TODO(), &results); err != nil {
6066
panic(err)
6167
}
6268
for _, result := range results {
63-
fmt.Println(result)
69+
res, _ := json.Marshal(result)
70+
fmt.Println(string(res))
6471
}
6572
//end skip
6673
}
6774

6875
fmt.Println("Aggegation Skip:")
6976
{
7077
// begin aggregate skip
71-
sortStage := bson.D{{"$sort", bson.D{{"rating", -1}}}}
72-
skipStage := bson.D{{"$skip", 3}}
78+
sortStage := bson.D{{"$sort", bson.D{{"enrollment", -1}}}}
79+
skipStage := bson.D{{"$skip", 1}}
7380

7481
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{sortStage, skipStage})
7582
if err != nil {
7683
panic(err)
7784
}
7885

79-
var results []bson.D
86+
var results []Course
8087
if err = cursor.All(context.TODO(), &results); err != nil {
8188
panic(err)
8289
}
8390
for _, result := range results {
84-
fmt.Println(result)
91+
res, _ := json.Marshal(result)
92+
fmt.Println(string(res))
8593
}
8694
// end aggregate skip
8795
}

0 commit comments

Comments
 (0)