diff --git a/source/crud/insert.txt b/source/crud/insert.txt index 6ce815b7..df8e2a9f 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -36,8 +36,8 @@ To learn how to use the ``BulkWrite()`` method, see the .. _golang-insert-id: -The ``_id`` Field ------------------ +The _id Field +------------- In MongoDB, each document *must* contain a unique ``_id`` field. @@ -105,8 +105,8 @@ The following example creates and inserts a document into the Inserted document with _id: ObjectID("...") -Modify ``InsertOne`` Behavior -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Modify InsertOne() Behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can modify the behavior of ``InsertOne()`` by constructing and passing an optional ``InsertOneOptions`` struct. The available options to set with ``InsertOneOptions`` are: @@ -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 ------------------------- @@ -174,8 +222,8 @@ After running the preceding code, your output resembles the following: Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...") -Modify ``InsertMany`` Behavior -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Modify InsertMany() Behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can modify the behavior of ``InsertMany()`` by constructing and passing an optional ``InsertManyOptions`` struct. The available options @@ -212,8 +260,8 @@ Construct an ``InsertManyOptions`` as follows: .. _golang-ordered-behavior: -``Ordered`` Behavior -~~~~~~~~~~~~~~~~~~~~ +Ordered Behavior +~~~~~~~~~~~~~~~~ Assume you want to insert the following documents: @@ -280,15 +328,60 @@ inserted into your collection. { "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } +Insert Many Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Additional Information ----------------------- +.. 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: -For runnable examples of the insert operations, see the following usage -examples: + .. output:: + :language: none + :visible: false -- :ref:`golang-insert-one` -- :ref:`golang-insert-many` + 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 +---------------------- To learn more about performing the operations mentioned, see the following guides: diff --git a/source/includes/usage-examples/code-snippets/insertMany.go b/source/includes/usage-examples/code-snippets/insertMany.go index 577dab73..e515f601 100644 --- a/source/includes/usage-examples/code-snippets/insertMany.go +++ b/source/includes/usage-examples/code-snippets/insertMany.go @@ -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"` @@ -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") @@ -44,7 +42,6 @@ func main() { } }() - // begin insertMany coll := client.Database("sample_restaurants").Collection("restaurants") // Creates two sample documents describing restaurants @@ -58,7 +55,6 @@ 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)) @@ -66,6 +62,9 @@ func main() { fmt.Printf("\t%s\n", id) } - // When you run this file, it should print: - // 2 documents inserted with IDs: ObjectID("..."), ObjectID("...") + // When you run this file for the first time, it should print output similar + // to the following: + // 2 documents inserted with IDs: + // ObjectID("...") + // ObjectID("...") } diff --git a/source/includes/usage-examples/code-snippets/insertManyBsonD.go b/source/includes/usage-examples/code-snippets/insertManyBsonD.go new file mode 100644 index 00000000..5b18f1f3 --- /dev/null +++ b/source/includes/usage-examples/code-snippets/insertManyBsonD.go @@ -0,0 +1,67 @@ +// 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) + } + + // When you run this file for the first time, it should print output similar + // to the following: + // 2 documents inserted with IDs: + // ObjectID("...") + // ObjectID("...") +} diff --git a/source/includes/usage-examples/code-snippets/insertOne.go b/source/includes/usage-examples/code-snippets/insertOne.go index 41493f85..55cee6ed 100644 --- a/source/includes/usage-examples/code-snippets/insertOne.go +++ b/source/includes/usage-examples/code-snippets/insertOne.go @@ -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"` @@ -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") @@ -45,7 +43,6 @@ 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"} @@ -53,11 +50,12 @@ func main() { 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: + // When you run this file for the first time, it should print output similar + // to the following: // Document inserted with ID: ObjectID("...") + } diff --git a/source/includes/usage-examples/code-snippets/insertOneBsonD.go b/source/includes/usage-examples/code-snippets/insertOneBsonD.go new file mode 100644 index 00000000..3e30e03f --- /dev/null +++ b/source/includes/usage-examples/code-snippets/insertOneBsonD.go @@ -0,0 +1,54 @@ +// 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) + + // When you run this file for the first time, it should print output similar + // to the following: + // Document inserted with ID: ObjectID("...") +}