Skip to content

Commit 49611a8

Browse files
authored
DOCSP-51816 Move and standardize insert usage examples (#538)
1 parent c8365c3 commit 49611a8

File tree

5 files changed

+238
-27
lines changed

5 files changed

+238
-27
lines changed

source/crud/insert.txt

Lines changed: 107 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ To learn how to use the ``BulkWrite()`` method, see the
3636

3737
.. _golang-insert-id:
3838

39-
The ``_id`` Field
40-
-----------------
39+
The _id Field
40+
-------------
4141

4242
In MongoDB, each document *must* contain a unique ``_id`` field.
4343

@@ -105,8 +105,8 @@ The following example creates and inserts a document into the
105105

106106
Inserted document with _id: ObjectID("...")
107107

108-
Modify ``InsertOne`` Behavior
109-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108+
Modify InsertOne() Behavior
109+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
110110
You can modify the behavior of ``InsertOne()`` by constructing and passing
111111
an optional ``InsertOneOptions`` struct. The available options to set with
112112
``InsertOneOptions`` are:
@@ -133,6 +133,54 @@ Construct an ``InsertOneOptions`` as follows:
133133
:copyable:
134134
:dedent:
135135

136+
Insert a Document Example: Full File
137+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
138+
139+
.. include:: /includes/usage-examples/example-intro.rst
140+
141+
The following example inserts a new document into the ``restaurants`` collection.
142+
Select the :guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:
143+
144+
.. tabs::
145+
146+
.. tab:: Struct
147+
:tabid: structExample
148+
149+
The following code uses a struct to insert a new document into the
150+
``restaurants`` collection:
151+
152+
.. io-code-block::
153+
:copyable: true
154+
155+
.. input:: /includes/usage-examples/code-snippets/insertOne.go
156+
:language: go
157+
:dedent:
158+
159+
.. output::
160+
:language: none
161+
:visible: false
162+
163+
Document inserted with ID: ObjectID("...")
164+
165+
.. tab:: bson.D
166+
:tabid: bsonDExample
167+
168+
The following code uses a ``bson.D`` type to insert a new document into the
169+
``restaurants`` collection:
170+
171+
.. io-code-block::
172+
:copyable: true
173+
174+
.. input:: /includes/usage-examples/code-snippets/insertOneBsonD.go
175+
:language: go
176+
:dedent:
177+
178+
.. output::
179+
:language: none
180+
:visible: false
181+
182+
Document inserted with ID: ObjectID("...")
183+
136184
Insert Multiple Documents
137185
-------------------------
138186

@@ -174,8 +222,8 @@ After running the preceding code, your output resembles the following:
174222
Inserted document with _id: ObjectID("...")
175223
Inserted document with _id: ObjectID("...")
176224

177-
Modify ``InsertMany`` Behavior
178-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
225+
Modify InsertMany() Behavior
226+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
179227

180228
You can modify the behavior of ``InsertMany()`` by constructing
181229
and passing an optional ``InsertManyOptions`` struct. The available options
@@ -212,8 +260,8 @@ Construct an ``InsertManyOptions`` as follows:
212260

213261
.. _golang-ordered-behavior:
214262

215-
``Ordered`` Behavior
216-
~~~~~~~~~~~~~~~~~~~~
263+
Ordered Behavior
264+
~~~~~~~~~~~~~~~~
217265

218266
Assume you want to insert the following documents:
219267

@@ -280,15 +328,60 @@ inserted into your collection.
280328
{ "_id": 1, "title": "Where the Wild Things Are" }
281329
{ "_id": 2, "title": "The Very Hungry Caterpillar" }
282330

331+
Insert Many Example: Full File
332+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283333

284-
Additional Information
285-
----------------------
334+
.. include:: /includes/usage-examples/example-intro.rst
335+
336+
The following example inserts multiple new documents into the ``restaurants`` collection.
337+
Select the :guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:
338+
339+
.. tabs::
340+
341+
.. tab:: Struct
342+
:tabid: structExample
343+
344+
The following code uses a struct to insert multiple new documents into the
345+
``restaurants`` collection:
346+
347+
.. io-code-block::
348+
:copyable: true
349+
350+
.. input:: /includes/usage-examples/code-snippets/insertMany.go
351+
:language: go
352+
:dedent:
286353

287-
For runnable examples of the insert operations, see the following usage
288-
examples:
354+
.. output::
355+
:language: none
356+
:visible: false
289357

290-
- :ref:`golang-insert-one`
291-
- :ref:`golang-insert-many`
358+
2 documents inserted with IDs:
359+
ObjectID("...")
360+
ObjectID("...")
361+
362+
.. tab:: bson.D
363+
:tabid: bsonDExample
364+
365+
The following code uses a ``bson.D`` type to insert multiple new documents into the
366+
``restaurants`` collection:
367+
368+
.. io-code-block::
369+
:copyable: true
370+
371+
.. input:: /includes/usage-examples/code-snippets/insertManyBsonD.go
372+
:language: go
373+
:dedent:
374+
375+
.. output::
376+
:language: none
377+
:visible: false
378+
379+
2 documents inserted with IDs:
380+
ObjectID("...")
381+
ObjectID("...")
382+
383+
Additional Information
384+
----------------------
292385

293386
To learn more about performing the operations mentioned, see the
294387
following guides:

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

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"go.mongodb.org/mongo-driver/v2/mongo/options"
1313
)
1414

15-
// start-restaurant-struct
15+
// Defines the structure of a restaurant document
1616
type Restaurant struct {
1717
Name string
1818
RestaurantId string `bson:"restaurant_id,omitempty"`
@@ -22,8 +22,6 @@ type Restaurant struct {
2222
Grades []interface{} `bson:"grades,omitempty"`
2323
}
2424

25-
// end-restaurant-struct
26-
2725
func main() {
2826
if err := godotenv.Load(); err != nil {
2927
log.Println("No .env file found")
@@ -44,7 +42,6 @@ func main() {
4442
}
4543
}()
4644

47-
// begin insertMany
4845
coll := client.Database("sample_restaurants").Collection("restaurants")
4946

5047
// Creates two sample documents describing restaurants
@@ -58,14 +55,16 @@ func main() {
5855
if err != nil {
5956
panic(err)
6057
}
61-
// end insertMany
6258

6359
// Prints the IDs of the inserted documents
6460
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
6561
for _, id := range result.InsertedIDs {
6662
fmt.Printf("\t%s\n", id)
6763
}
6864

69-
// When you run this file, it should print:
70-
// 2 documents inserted with IDs: ObjectID("..."), ObjectID("...")
65+
// When you run this file for the first time, it should print output similar
66+
// to the following:
67+
// 2 documents inserted with IDs:
68+
// ObjectID("...")
69+
// ObjectID("...")
7170
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Inserts sample documents describing restaurants by using the Go driver with bson.D
2+
package main
3+
4+
import (
5+
"context"
6+
"fmt"
7+
"log"
8+
"os"
9+
10+
"github.com/joho/godotenv"
11+
"go.mongodb.org/mongo-driver/v2/bson"
12+
"go.mongodb.org/mongo-driver/v2/mongo"
13+
"go.mongodb.org/mongo-driver/v2/mongo/options"
14+
)
15+
16+
func main() {
17+
if err := godotenv.Load(); err != nil {
18+
log.Println("No .env file found")
19+
}
20+
21+
var uri string
22+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
23+
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")
24+
}
25+
26+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
27+
if err != nil {
28+
panic(err)
29+
}
30+
defer func() {
31+
if err = client.Disconnect(context.TODO()); err != nil {
32+
panic(err)
33+
}
34+
}()
35+
36+
coll := client.Database("sample_restaurants").Collection("restaurants")
37+
38+
// Creates two sample documents describing restaurants using bson.D
39+
newRestaurants := []interface{}{
40+
bson.D{
41+
bson.E{Key: "name", Value: "Rule of Thirds"},
42+
bson.E{Key: "cuisine", Value: "Japanese"},
43+
},
44+
bson.D{
45+
bson.E{Key: "name", Value: "Madame Vo"},
46+
bson.E{Key: "cuisine", Value: "Vietnamese"},
47+
},
48+
}
49+
50+
// Inserts sample documents into the collection
51+
result, err := coll.InsertMany(context.TODO(), newRestaurants)
52+
if err != nil {
53+
panic(err)
54+
}
55+
56+
// Prints the IDs of the inserted documents
57+
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
58+
for _, id := range result.InsertedIDs {
59+
fmt.Printf("\t%s\n", id)
60+
}
61+
62+
// When you run this file for the first time, it should print output similar
63+
// to the following:
64+
// 2 documents inserted with IDs:
65+
// ObjectID("...")
66+
// ObjectID("...")
67+
}

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"go.mongodb.org/mongo-driver/v2/mongo/options"
1313
)
1414

15-
// start-restaurant-struct
15+
// Defines the structure of a restaurant document
1616
type Restaurant struct {
1717
Name string
1818
RestaurantId string `bson:"restaurant_id,omitempty"`
@@ -22,8 +22,6 @@ type Restaurant struct {
2222
Grades []interface{} `bson:"grades,omitempty"`
2323
}
2424

25-
// end-restaurant-struct
26-
2725
func main() {
2826
if err := godotenv.Load(); err != nil {
2927
log.Println("No .env file found")
@@ -45,19 +43,19 @@ func main() {
4543
}()
4644

4745
// Inserts a sample document describing a restaurant into the collection
48-
// begin insertOne
4946
coll := client.Database("sample_restaurants").Collection("restaurants")
5047
newRestaurant := Restaurant{Name: "8282", Cuisine: "Korean"}
5148

5249
result, err := coll.InsertOne(context.TODO(), newRestaurant)
5350
if err != nil {
5451
panic(err)
5552
}
56-
// end insertOne
5753

5854
// Prints the ID of the inserted document
5955
fmt.Printf("Document inserted with ID: %s\n", result.InsertedID)
6056

61-
// When you run this file, it should print:
57+
// When you run this file for the first time, it should print output similar
58+
// to the following:
6259
// Document inserted with ID: ObjectID("...")
60+
6361
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Inserts a single document describing a restaurant by using the Go driver with bson.D
2+
package main
3+
4+
import (
5+
"context"
6+
"fmt"
7+
"log"
8+
"os"
9+
10+
"github.com/joho/godotenv"
11+
"go.mongodb.org/mongo-driver/v2/bson"
12+
"go.mongodb.org/mongo-driver/v2/mongo"
13+
"go.mongodb.org/mongo-driver/v2/mongo/options"
14+
)
15+
16+
func main() {
17+
if err := godotenv.Load(); err != nil {
18+
log.Println("No .env file found")
19+
}
20+
21+
var uri string
22+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
23+
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")
24+
}
25+
26+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
27+
if err != nil {
28+
panic(err)
29+
}
30+
defer func() {
31+
if err = client.Disconnect(context.TODO()); err != nil {
32+
panic(err)
33+
}
34+
}()
35+
36+
// Inserts a sample document describing a restaurant into the collection using bson.D
37+
coll := client.Database("sample_restaurants").Collection("restaurants")
38+
newRestaurant := bson.D{
39+
bson.E{Key: "name", Value: "8282"},
40+
bson.E{Key: "cuisine", Value: "Korean"},
41+
}
42+
43+
result, err := coll.InsertOne(context.TODO(), newRestaurant)
44+
if err != nil {
45+
panic(err)
46+
}
47+
48+
// Prints the ID of the inserted document
49+
fmt.Printf("Document inserted with ID: %s\n", result.InsertedID)
50+
51+
// When you run this file for the first time, it should print output similar
52+
// to the following:
53+
// Document inserted with ID: ObjectID("...")
54+
}

0 commit comments

Comments
 (0)