Skip to content

Commit 42d6f98

Browse files
committed
DOCSP-51815 Move and standardize find usage exs
1 parent 61b2f4c commit 42d6f98

File tree

5 files changed

+281
-12
lines changed

5 files changed

+281
-12
lines changed

source/crud/query/retrieve.txt

Lines changed: 132 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ consist of the ``Find()`` and ``FindOne()`` methods.
6262

6363
.. _golang-find-example:
6464

65-
Find All Documents
66-
~~~~~~~~~~~~~~~~~~
65+
Find Multiple Documents
66+
~~~~~~~~~~~~~~~~~~~~~~~
6767

6868
The ``Find()`` method expects you to pass a ``Context`` type and a
6969
query filter. The method returns *all* documents that match the filter
@@ -94,6 +94,67 @@ the ``Find()`` method, which performs the following actions:
9494

9595
To learn how to access data by using a cursor, see the :ref:`golang-cursor` guide.
9696

97+
Find Multiple Documents Example: Full File
98+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
99+
100+
.. include:: /includes/usage-examples/example-intro.rst
101+
102+
The following example finds documents in the ``restaurants`` collection
103+
in which the ``cuisine`` is ``"Italian"``, returns a cursor that
104+
references the matched documents, then unpacks the documents into a slice.
105+
Select the **Struct** or **bson.D** tab to see the corresponding code:
106+
107+
.. tabs::
108+
109+
.. tab :: Struct
110+
:tabid: structExample
111+
112+
The following code uses structs to find documents in the ``restaurants`` collection
113+
in which the ``cuisine`` is "Italian", returning all documents that match:
114+
115+
.. io-code-block::
116+
:copyable: true
117+
118+
.. input:: /includes/usage-examples/code-snippets/find.go
119+
:language: go
120+
:dedent:
121+
122+
.. output::
123+
:language: none
124+
:visible: false
125+
126+
// results truncated
127+
...
128+
{ ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... },
129+
{ ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... },
130+
{ ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... },
131+
...
132+
133+
.. tab :: bson.D
134+
:tabid: bsonDExample
135+
136+
The following code uses a bson.D type to find documents in the ``restaurants``
137+
collection in which the ``cuisine`` is "Italian", returning all documents
138+
that match:
139+
140+
.. io-code-block::
141+
:copyable: true
142+
143+
.. input:: /includes/usage-examples/code-snippets/findBsonD.go
144+
:language: go
145+
:dedent:
146+
147+
.. output::
148+
:language: none
149+
:visible: false
150+
151+
// results truncated
152+
...
153+
{ ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... },
154+
{ ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... },
155+
{ ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... },
156+
...
157+
97158
.. _golang-find-one-example:
98159

99160
Find One Document
@@ -182,6 +243,75 @@ as parameters to the ``FindOne()`` method to perform the following actions:
182243
about the ``_id`` field, see the :ref:`_id Field <golang-insert-id>`
183244
section of the Insert a Document page.
184245

246+
Find One Document Example: Full File
247+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
248+
249+
.. include:: /includes/usage-examples/example-intro.rst
250+
251+
The following example finds a document that matches a query filter in the
252+
``restaurants`` collection. Select the **Struct** or **bson.D** tab to see the
253+
corresponding code:
254+
255+
.. tabs::
256+
257+
.. tab :: Struct
258+
:tabid: structExample
259+
260+
The following code uses structs to find documents in the ``restaurants`` collection
261+
in which the ``name`` is "Bagels N Buns", returning the first document
262+
matched:
263+
264+
.. io-code-block::
265+
:copyable: true
266+
267+
.. input:: /includes/usage-examples/code-snippets/findOne.go
268+
:language: go
269+
:dedent:
270+
271+
.. output::
272+
:language: none
273+
:visible: false
274+
275+
// results truncated
276+
{
277+
"ID": "5eb3d668b31de5d588f42950",
278+
"Name": "Bagels N Buns",
279+
"RestaurantId": "40363427"
280+
"Address": [...],
281+
"Borough": "Staten Island",
282+
"Cuisine": "Delicatessen",
283+
"Grades": [...]
284+
}
285+
286+
.. tab :: bson.D
287+
:tabid: bsonDExample
288+
289+
The following code uses a bson.D type to find documents in the ``restaurants`` collection
290+
in which the ``name`` is "Bagels N Buns", returning the first document
291+
matched:
292+
293+
.. io-code-block::
294+
:copyable: true
295+
296+
.. input:: /includes/usage-examples/code-snippets/findOneBsonD.go
297+
:language: go
298+
:dedent:
299+
300+
.. output::
301+
:language: none
302+
:visible: false
303+
304+
// results truncated
305+
{
306+
"ID": "5eb3d668b31de5d588f42950",
307+
"Name": "Bagels N Buns",
308+
"RestaurantId": "40363427"
309+
"Address": [...],
310+
"Borough": "Staten Island",
311+
"Cuisine": "Delicatessen",
312+
"Grades": [...]
313+
}
314+
185315
.. _golang-retrieve-options:
186316

187317
Modify Behavior

source/includes/usage-examples/code-snippets/find.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// begin find
12
// Retrieves documents that match a query filter by using the Go driver
23
package main
34

@@ -14,7 +15,7 @@ import (
1415
"go.mongodb.org/mongo-driver/v2/mongo/options"
1516
)
1617

17-
// start-restaurant-struct
18+
// Creates a Restaurant struct as a model for documents in the restaurants collection
1819
type Restaurant struct {
1920
ID bson.ObjectID `bson:"_id"`
2021
Name string
@@ -25,7 +26,10 @@ type Restaurant struct {
2526
Grades interface{}
2627
}
2728

28-
// end-restaurant-struct
29+
// Creates a filter struct to use for the query
30+
type RestaurantCuisineFilter struct {
31+
Cuisine string
32+
}
2933

3034
func main() {
3135
if err := godotenv.Load(); err != nil {
@@ -47,12 +51,11 @@ func main() {
4751
}
4852
}()
4953

50-
// begin find
5154
coll := client.Database("sample_restaurants").Collection("restaurants")
5255

5356
// Creates a query filter to match documents in which the "cuisine"
5457
// is "Italian"
55-
filter := bson.D{{"cuisine", "Italian"}}
58+
filter := RestaurantCuisineFilter{Cuisine: "Italian"}
5659

5760
// Retrieves documents that match the query filter
5861
cursor, err := coll.Find(context.TODO(), filter)
@@ -65,7 +68,6 @@ func main() {
6568
if err = cursor.All(context.TODO(), &results); err != nil {
6669
panic(err)
6770
}
68-
// end find
6971

7072
// Prints the results of the find operation as structs
7173
for _, result := range results {
@@ -77,3 +79,5 @@ func main() {
7779
fmt.Printf("%s\n", output)
7880
}
7981
}
82+
83+
// end find
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// begin find
2+
// Retrieves documents that match a query filter by using the Go driver
3+
package main
4+
5+
import (
6+
"context"
7+
"encoding/json"
8+
"fmt"
9+
"log"
10+
"os"
11+
12+
"github.com/joho/godotenv"
13+
"go.mongodb.org/mongo-driver/v2/bson"
14+
"go.mongodb.org/mongo-driver/v2/mongo"
15+
"go.mongodb.org/mongo-driver/v2/mongo/options"
16+
)
17+
18+
func main() {
19+
if err := godotenv.Load(); err != nil {
20+
log.Println("No .env file found")
21+
}
22+
23+
var uri string
24+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
25+
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable")
26+
}
27+
28+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
29+
if err != nil {
30+
panic(err)
31+
}
32+
defer func() {
33+
if err = client.Disconnect(context.TODO()); err != nil {
34+
panic(err)
35+
}
36+
}()
37+
38+
coll := client.Database("sample_restaurants").Collection("restaurants")
39+
40+
// Creates a query filter to match documents in which the "cuisine"
41+
// is "Italian"
42+
filter := bson.D{{"cuisine", "Italian"}}
43+
44+
// Retrieves documents that match the query filter
45+
cursor, err := coll.Find(context.TODO(), filter)
46+
if err != nil {
47+
panic(err)
48+
}
49+
50+
// Unpacks the cursor into a slice
51+
var results []Restaurant
52+
if err = cursor.All(context.TODO(), &results); err != nil {
53+
panic(err)
54+
}
55+
56+
// Prints the results of the find operation as structs
57+
for _, result := range results {
58+
cursor.Decode(&result)
59+
output, err := json.MarshalIndent(result, "", " ")
60+
if err != nil {
61+
panic(err)
62+
}
63+
fmt.Printf("%s\n", output)
64+
}
65+
}
66+
67+
// end find

source/includes/usage-examples/code-snippets/findOne.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// begin findOne
12
// Retrieves a document that matches a query filter by using the Go driver
23
package main
34

@@ -14,7 +15,7 @@ import (
1415
"go.mongodb.org/mongo-driver/v2/mongo/options"
1516
)
1617

17-
// start-restaurant-struct
18+
// Creates a Restaurant struct as a model for documents in the restaurants collection
1819
type Restaurant struct {
1920
ID bson.ObjectID `bson:"_id"`
2021
Name string
@@ -25,7 +26,10 @@ type Restaurant struct {
2526
Grades []interface{}
2627
}
2728

28-
// end-restaurant-struct
29+
// Creates a filter struct to use for the query
30+
type RestaurantNameFilter struct {
31+
Name string
32+
}
2933

3034
func main() {
3135
if err := godotenv.Load(); err != nil {
@@ -47,12 +51,11 @@ func main() {
4751
}
4852
}()
4953

50-
// begin findOne
5154
coll := client.Database("sample_restaurants").Collection("restaurants")
5255

5356
// Creates a query filter to match documents in which the "name" is
5457
// "Bagels N Buns"
55-
filter := bson.D{{"name", "Bagels N Buns"}}
58+
filter := RestaurantNameFilter{Name: "Bagels N Buns"}
5659

5760
// Retrieves the first matching document
5861
var result Restaurant
@@ -66,11 +69,12 @@ func main() {
6669
}
6770
panic(err)
6871
}
69-
// end findOne
7072

7173
output, err := json.MarshalIndent(result, "", " ")
7274
if err != nil {
7375
panic(err)
7476
}
7577
fmt.Printf("%s\n", output)
7678
}
79+
80+
// end findOne
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// begin findOne
2+
// Retrieves a document that matches a query filter by using the Go driver
3+
package main
4+
5+
import (
6+
"context"
7+
"encoding/json"
8+
"fmt"
9+
"log"
10+
"os"
11+
12+
"github.com/joho/godotenv"
13+
"go.mongodb.org/mongo-driver/v2/bson"
14+
"go.mongodb.org/mongo-driver/v2/mongo"
15+
"go.mongodb.org/mongo-driver/v2/mongo/options"
16+
)
17+
18+
func main() {
19+
if err := godotenv.Load(); err != nil {
20+
log.Println("No .env file found")
21+
}
22+
23+
var uri string
24+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
25+
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable")
26+
}
27+
28+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
29+
if err != nil {
30+
panic(err)
31+
}
32+
defer func() {
33+
if err = client.Disconnect(context.TODO()); err != nil {
34+
panic(err)
35+
}
36+
}()
37+
38+
coll := client.Database("sample_restaurants").Collection("restaurants")
39+
40+
// Creates a query filter to match documents in which the "name" is
41+
// "Bagels N Buns"
42+
filter := bson.D{{"name", "Bagels N Buns"}}
43+
44+
// Retrieves the first matching document
45+
var result Restaurant
46+
err = coll.FindOne(context.TODO(), filter).Decode(&result)
47+
48+
// Prints a message if no documents are matched or if any
49+
// other errors occur during the operation
50+
if err != nil {
51+
if err == mongo.ErrNoDocuments {
52+
return
53+
}
54+
panic(err)
55+
}
56+
57+
output, err := json.MarshalIndent(result, "", " ")
58+
if err != nil {
59+
panic(err)
60+
}
61+
fmt.Printf("%s\n", output)
62+
}
63+
64+
// end findOne

0 commit comments

Comments
 (0)