Skip to content

DOCSP-51816 Move and standardize insert usage examples #538

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions source/crud/insert.txt
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,54 @@ Construct an ``InsertOneOptions`` as follows:
:copyable:
:dedent:

Insert a Document Example: Full File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. include:: /includes/usage-examples/example-intro.rst

The following example inserts a new document into the ``restaurants`` collection.
Select the :guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:

.. tabs::

.. tab:: Struct
:tabid: structExample

The following code uses a struct to insert a new document into the
``restaurants`` collection:

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/insertOne.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

Document inserted with ID: ObjectID("...")

.. tab:: bson.D
:tabid: bsonDExample

The following code uses a ``bson.D`` type to insert a new document into the
``restaurants`` collection:

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/insertOneBsonD.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

Document inserted with ID: ObjectID("...")

Insert Multiple Documents
-------------------------

Expand Down Expand Up @@ -280,6 +328,57 @@ inserted into your collection.
{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }

Insert Many Example: Full File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. include:: /includes/usage-examples/example-intro.rst

The following example inserts multiple new documents into the ``restaurants`` collection.
Select the :guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:

.. tabs::

.. tab:: Struct
:tabid: structExample

The following code uses a struct to insert multiple new documents into the
``restaurants`` collection:

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/insertMany.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

2 documents inserted with IDs:
ObjectID("...")
ObjectID("...")

.. tab:: bson.D
:tabid: bsonDExample

The following code uses a ``bson.D`` type to insert multiple new documents into the
``restaurants`` collection:

.. io-code-block::
:copyable: true

.. input:: /includes/usage-examples/code-snippets/insertManyBsonD.go
:language: go
:dedent:

.. output::
:language: none
:visible: false

2 documents inserted with IDs:
ObjectID("...")
ObjectID("...")

Additional Information
----------------------
Expand Down
8 changes: 1 addition & 7 deletions source/includes/usage-examples/code-snippets/insertMany.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// start-restaurant-struct
// Defines the structure of a restaurant document
type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Expand All @@ -22,8 +22,6 @@ type Restaurant struct {
Grades []interface{} `bson:"grades,omitempty"`
}

// end-restaurant-struct

func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
Expand All @@ -44,7 +42,6 @@ func main() {
}
}()

// begin insertMany
coll := client.Database("sample_restaurants").Collection("restaurants")

// Creates two sample documents describing restaurants
Expand All @@ -58,14 +55,11 @@ func main() {
if err != nil {
panic(err)
}
// end insertMany

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

// When you run this file, it should print:
// 2 documents inserted with IDs: ObjectID("..."), ObjectID("...")
}
62 changes: 62 additions & 0 deletions source/includes/usage-examples/code-snippets/insertManyBsonD.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Inserts sample documents describing restaurants by using the Go driver with bson.D
package main

import (
"context"
"fmt"
"log"
"os"

"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}

var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
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")
}

client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()

coll := client.Database("sample_restaurants").Collection("restaurants")

// Creates two sample documents describing restaurants using bson.D
newRestaurants := []interface{}{
bson.D{
bson.E{Key: "name", Value: "Rule of Thirds"},
bson.E{Key: "cuisine", Value: "Japanese"},
},
bson.D{
bson.E{Key: "name", Value: "Madame Vo"},
bson.E{Key: "cuisine", Value: "Vietnamese"},
},
}

// Inserts sample documents into the collection
result, err := coll.InsertMany(context.TODO(), newRestaurants)
if err != nil {
panic(err)
}

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

}
8 changes: 1 addition & 7 deletions source/includes/usage-examples/code-snippets/insertOne.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// start-restaurant-struct
// Defines the structure of a restaurant documen
type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Expand All @@ -22,8 +22,6 @@ type Restaurant struct {
Grades []interface{} `bson:"grades,omitempty"`
}

// end-restaurant-struct

func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
Expand All @@ -45,19 +43,15 @@ func main() {
}()

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

result, err := coll.InsertOne(context.TODO(), newRestaurant)
if err != nil {
panic(err)
}
// end insertOne

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

// When you run this file, it should print:
// Document inserted with ID: ObjectID("...")
}
51 changes: 51 additions & 0 deletions source/includes/usage-examples/code-snippets/insertOneBsonD.go
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

S: I think we might still need the Restaurant data structure for the bson examples to aid the example. Not sure if we need to have it in BSON. I would ask the tech reviewer what they think.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, will check with them!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@prestonvasquez when you have a moment to do tech review, can you take a look at this feedback from Lindsey? Should the bson examples also include the Restaurant data structure? Thank you!

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Inserts a single document describing a restaurant by using the Go driver with bson.D
package main

import (
"context"
"fmt"
"log"
"os"

"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}

var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
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")
}

client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()

// Inserts a sample document describing a restaurant into the collection using bson.D
coll := client.Database("sample_restaurants").Collection("restaurants")
newRestaurant := bson.D{
bson.E{Key: "name", Value: "8282"},
bson.E{Key: "cuisine", Value: "Korean"},
}

result, err := coll.InsertOne(context.TODO(), newRestaurant)
if err != nil {
panic(err)
}

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

}
Loading