Skip to content

Commit 83952bd

Browse files
authored
DOCSP-26436: use struct in retrieve data pg (#212)
* DOCSP-26436: use struct in retrieve data pg * struct tag fix
1 parent 95ed6fc commit 83952bd

File tree

2 files changed

+93
-66
lines changed

2 files changed

+93
-66
lines changed

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

Lines changed: 57 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,17 @@ Read operations allow you to do the following:
2626
Sample Data
2727
~~~~~~~~~~~
2828

29+
The examples in this section use the following ``Review`` struct as a model for documents
30+
in the ``reviews`` collection:
31+
32+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
33+
:start-after: start-review-struct
34+
:end-before: end-review-struct
35+
:language: go
36+
:dedent:
37+
2938
To run the examples in this guide, load these documents into the
30-
``tea.ratings`` collection with the following
39+
``tea.reviews`` collection with the following
3140
snippet:
3241

3342
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
@@ -36,7 +45,11 @@ snippet:
3645
:start-after: begin insert docs
3746
:end-before: end insert docs
3847

39-
.. include:: /includes/fundamentals/tea-sample-data-ending.rst
48+
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
49+
50+
Each document describes the tea variety a customer ordered, their
51+
rating, and the date of the order. These descriptions correspond to the
52+
``item``, ``rating``, and ``date_ordered`` fields.
4053

4154
.. _golang-retrieve-find:
4255

@@ -109,14 +122,15 @@ following methods:
109122
- | The field and type of sort to order the matched documents. You can specify an ascending or descending sort.
110123
| Default: none
111124

112-
Example
113-
```````
125+
Find Example
126+
````````````
114127

115128
The following example passes a context, filter, and ``FindOptions`` to
116129
the ``Find()`` method, which performs the following actions:
117130

118-
- Matches documents where the ``rating`` falls between ``5`` and ``10``
119-
- Returns the ``type`` and ``rating``, but excludes the ``_id``
131+
- Matches documents where the ``rating`` value is between ``5`` and
132+
``9`` (exclusive)
133+
- Sorts matched documents in ascending order by ``date_ordered``
120134

121135
.. io-code-block::
122136
:copyable: true
@@ -125,69 +139,69 @@ the ``Find()`` method, which performs the following actions:
125139
:language: go
126140

127141
filter := bson.D{
128-
{"$and",
129-
bson.A{
130-
bson.D{{"rating", bson.D{{"$gt", 5}}}},
131-
bson.D{{"rating", bson.D{{"$lt", 10}}}},
132-
}},
142+
{"$and",
143+
bson.A{
144+
bson.D{{"rating", bson.D{{"$gt", 5}}}},
145+
bson.D{{"rating", bson.D{{"$lt", 9}}}},
146+
}},
133147
}
134-
projection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
135-
opts := options.Find().SetProjection(projection)
136-
148+
sort := bson.D{{"date_ordered", 1}}
149+
opts := options.Find().SetSort(sort)
150+
137151
cursor, err := coll.Find(context.TODO(), filter, opts)
138152
if err != nil {
139-
panic(err)
153+
panic(err)
140154
}
141-
142-
var results []bson.D
155+
156+
var results []Review
143157
if err = cursor.All(context.TODO(), &results); err != nil {
144-
panic(err)
158+
panic(err)
145159
}
146160
for _, result := range results {
147-
fmt.Println(result)
161+
res, _ := json.Marshal(result)
162+
fmt.Println(string(res))
148163
}
149164

150165
.. output::
151166
:language: none
152167
:visible: false
153168

154-
[{type Masala} {rating 7}]
155-
[{type Earl Grey} {rating 9}]
169+
{"Item":"Sencha","Rating":7,"DateOrdered":"2009-11-18T05:00:00Z"}
170+
{"Item":"Masala","Rating":8,"DateOrdered":"2009-12-01T05:00:00Z"}
156171

157-
Example
158-
```````
172+
Find One Example
173+
````````````````
159174

160175
The following example passes a context, filter, and ``FindOneOptions``
161176
to the ``FindOne()`` method, which performs the following actions:
162177

163-
- Matches all documents
164-
- A descending sort on the ``rating`` field
165-
- Returns the ``type`` and ``rating``, but excludes the ``_id``
178+
- Matches documents where the ``date_ordered`` value is on or before November
179+
30, 2009
180+
- Skips the first two matched documents
166181

167182
.. io-code-block::
168183
:copyable: true
169184

170185
.. input::
171186
:language: go
172187

173-
filter := bson.D{}
174-
sort := bson.D{{"rating", -1}}
175-
projection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
176-
opts := options.FindOne().SetSort(sort).SetProjection(projection)
177-
178-
var result bson.D
188+
filter := bson.D{{"date_ordered", bson.D{{"$lte", time.Date(2009, 11, 30, 0, 0, 0, 0, time.Local)}}}}
189+
opts := options.FindOne().SetSkip(2)
190+
191+
var result Review
179192
err := coll.FindOne(context.TODO(), filter, opts).Decode(&result)
180193
if err != nil {
181-
panic(err)
194+
panic(err)
182195
}
183-
184-
fmt.Println(result)
196+
197+
res, _ := json.Marshal(result)
198+
fmt.Println(string(res))
185199

186200
.. output::
187201
:language: none
188202
:visible: false
189203

190-
[{type Masala} {rating 10}]
204+
{"Item":"Masala","Rating":9,"DateOrdered":"2009-11-12T05:00:00Z"}
191205

192206
.. _golang-retrieve-aggregation:
193207

@@ -272,8 +286,8 @@ Example
272286
The following example passes a context and an aggregation pipeline that
273287
performs the following actions:
274288

275-
- Groups reviews by types
276-
- Calculates the average rating of each type
289+
- Groups reviews by item ordered
290+
- Calculates the average rating for each item
277291

278292
.. io-code-block::
279293
:copyable: true
@@ -283,7 +297,7 @@ performs the following actions:
283297

284298
groupStage := bson.D{
285299
{"$group", bson.D{
286-
{"_id", "$type"},
300+
{"_id", "$item"},
287301
{"average", bson.D{
288302
{"$avg", "$rating"},
289303
}},
@@ -299,15 +313,16 @@ performs the following actions:
299313
panic(err)
300314
}
301315
for _, result := range results {
302-
fmt.Printf("%v has an average rating of %v \n", result["_id"], result["average"])
316+
fmt.Printf("%v had an average rating of %v \n", result["_id"], result["average"])
303317
}
304318

305319
.. output::
306320
:language: none
307321
:visible: false
308322

309-
Masala has an average rating of 8.5
310-
Earl Grey has an average rating of 7
323+
Sencha had an average rating of 8.5
324+
Hibiscus had an average rating of 4
325+
Masala had an average rating of 9
311326

312327
To learn more about how to construct an aggregation pipeline, see
313328
the MongoDB server manual page on :manual:`Aggregation

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

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,26 @@ package main
22

33
import (
44
"context"
5+
"encoding/json"
56
"fmt"
67
"log"
78
"os"
9+
"time"
810

911
"go.mongodb.org/mongo-driver/bson"
1012
"go.mongodb.org/mongo-driver/mongo"
1113
"go.mongodb.org/mongo-driver/mongo/options"
1214
)
1315

16+
// start-review-struct
17+
type Review struct {
18+
Item string
19+
Rating int32
20+
DateOrdered time.Time `bson:"date_ordered"`
21+
}
22+
23+
// end-review-struct
24+
1425
func main() {
1526
var uri string
1627
if uri = os.Getenv("DRIVER_REF_URI"); uri == "" {
@@ -27,77 +38,78 @@ func main() {
2738
panic(err)
2839
}
2940
}()
30-
31-
client.Database("tea").Collection("ratings").Drop(context.TODO())
3241

3342
// begin insert docs
34-
coll := client.Database("tea").Collection("ratings")
43+
coll := client.Database("tea").Collection("reviews")
3544
docs := []interface{}{
36-
bson.D{{"type", "Masala"}, {"rating", 10}},
37-
bson.D{{"type", "Earl Grey"}, {"rating", 5}},
38-
bson.D{{"type", "Masala"}, {"rating", 7}},
39-
bson.D{{"type", "Earl Grey"}, {"rating", 9}},
45+
Review{Item: "Masala", Rating: 10, DateOrdered: time.Date(2009, 11, 17, 0, 0, 0, 0, time.Local)},
46+
Review{Item: "Sencha", Rating: 7, DateOrdered: time.Date(2009, 11, 18, 0, 0, 0, 0, time.Local)},
47+
Review{Item: "Masala", Rating: 9, DateOrdered: time.Date(2009, 11, 12, 0, 0, 0, 0, time.Local)},
48+
Review{Item: "Masala", Rating: 8, DateOrdered: time.Date(2009, 12, 1, 0, 0, 0, 0, time.Local)},
49+
Review{Item: "Sencha", Rating: 10, DateOrdered: time.Date(2009, 12, 17, 0, 0, 0, 0, time.Local)},
50+
Review{Item: "Hibiscus", Rating: 4, DateOrdered: time.Date(2009, 12, 18, 0, 0, 0, 0, time.Local)},
4051
}
4152

4253
result, err := coll.InsertMany(context.TODO(), docs)
54+
// end insert docs
55+
4356
if err != nil {
4457
panic(err)
4558
}
4659
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
47-
// end insert docs
4860

49-
fmt.Println("Find:")
61+
fmt.Println("\nFind:\n")
5062
{
5163
// begin find docs
5264
filter := bson.D{
5365
{"$and",
5466
bson.A{
5567
bson.D{{"rating", bson.D{{"$gt", 5}}}},
56-
bson.D{{"rating", bson.D{{"$lt", 10}}}},
68+
bson.D{{"rating", bson.D{{"$lt", 9}}}},
5769
}},
5870
}
59-
projection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
60-
opts := options.Find().SetProjection(projection)
71+
sort := bson.D{{"date_ordered", 1}}
72+
opts := options.Find().SetSort(sort)
6173

6274
cursor, err := coll.Find(context.TODO(), filter, opts)
6375
if err != nil {
6476
panic(err)
6577
}
6678

67-
var results []bson.D
79+
var results []Review
6880
if err = cursor.All(context.TODO(), &results); err != nil {
6981
panic(err)
7082
}
7183
for _, result := range results {
72-
fmt.Println(result)
84+
res, _ := json.Marshal(result)
85+
fmt.Println(string(res))
7386
}
7487
// end find docs
7588
}
7689

77-
fmt.Println("Find One:")
90+
fmt.Println("\nFind One:\n")
7891
{
7992
// begin find one docs
80-
filter := bson.D{}
81-
sort := bson.D{{"rating", -1}}
82-
projection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
83-
opts := options.FindOne().SetSort(sort).SetProjection(projection)
93+
filter := bson.D{{"date_ordered", bson.D{{"$lte", time.Date(2009, 11, 30, 0, 0, 0, 0, time.Local)}}}}
94+
opts := options.FindOne().SetSkip(2)
8495

85-
var result bson.D
96+
var result Review
8697
err := coll.FindOne(context.TODO(), filter, opts).Decode(&result)
8798
if err != nil {
8899
panic(err)
89100
}
90101

91-
fmt.Println(result)
102+
res, _ := json.Marshal(result)
103+
fmt.Println(string(res))
92104
// end find one docs
93105
}
94106

95-
fmt.Println("Aggregation:")
107+
fmt.Println("\nAggregation:\n")
96108
{
97109
// begin aggregate docs
98110
groupStage := bson.D{
99111
{"$group", bson.D{
100-
{"_id", "$type"},
112+
{"_id", "$item"},
101113
{"average", bson.D{
102114
{"$avg", "$rating"},
103115
}},
@@ -113,7 +125,7 @@ func main() {
113125
panic(err)
114126
}
115127
for _, result := range results {
116-
fmt.Printf("%v has an average rating of %v \n", result["_id"], result["average"])
128+
fmt.Printf("%v had an average rating of %v \n", result["_id"], result["average"])
117129
}
118130
// end aggregate docs
119131
}

0 commit comments

Comments
 (0)