diff --git a/source/crud/update.txt b/source/crud/update.txt index 100be569..910b23cb 100644 --- a/source/crud/update.txt +++ b/source/crud/update.txt @@ -204,28 +204,99 @@ The following shows the updated document resulting from the preceding update ope ... } -UpdateMany() Example --------------------- +UpdateOne() Example: Full File +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The following example uses the ``listingsAndReviews`` collection in the -``sample_airbnb`` dataset from the :atlas:`Atlas sample datasets `. +.. include:: /includes/usage-examples/example-intro.rst + +The following example is a fully runnable file that finds and updates an +existing document in 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 define the filter and update a document in the ``restuarants`` collection: + + .. io-code-block:: + :copyable: true + + .. input:: /includes/usage-examples/code-snippets/updateOne.go + :language: go + :dedent: + + .. output:: + :language: none + :visible: false + + Documents updated: 1 + + .. tab:: bson.D + :tabid: bsonDExample + + The following code uses a ``bson.D`` type to define the filter and update a document in the ``restuarants`` collection: + + .. io-code-block:: + :copyable: true + + .. input:: /includes/usage-examples/code-snippets/updateOneBson.go + :language: go + :dedent: + + .. output:: + :language: none + :visible: false + + Documents updated: 1 + +UpdateMany() Example: Full File +------------------------------- + +.. include:: /includes/usage-examples/example-intro.rst + +The following example is a fully runnable file that finds and updates multiple +exisiting documents in 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 define the filter and update multiple documents in the ``restuarants`` collection: + + .. io-code-block:: + :copyable: true + + .. input:: /includes/usage-examples/code-snippets/updateMany.go + :language: go + :dedent: + + .. output:: + :language: none + :visible: false + + Documents updated: 296 + + .. tab:: bson.D + :tabid: bsonDExample -The following example uses the ``UpdateMany()`` method to: + The following code uses a ``bson.D`` type to define the filter and update multiple documents in the ``restuarants`` collection: -- Match documents in which the value of the ``address.market`` field is ``"Sydney"``. -- Multiply the ``price`` value in the matched documents by ``1.15`` + .. io-code-block:: + :copyable: true -.. literalinclude:: /includes/usage-examples/code-snippets/updateMany.go - :start-after: begin updatemany - :end-before: end updatemany - :emphasize-lines: 9 - :language: go - :copyable: - :dedent: + .. input:: /includes/usage-examples/code-snippets/updateManyBson.go + :language: go + :dedent: -The update operation updates ``609`` documents. + .. output:: + :language: none + :visible: false -To learn more about how to retrieve multiple documents, see :ref:`golang-find-example`. + Documents updated: 296 Additional Information ---------------------- diff --git a/source/includes/usage-examples/code-snippets/updateMany.go b/source/includes/usage-examples/code-snippets/updateMany.go index fdf4d235..a6f19ad4 100644 --- a/source/includes/usage-examples/code-snippets/updateMany.go +++ b/source/includes/usage-examples/code-snippets/updateMany.go @@ -13,6 +13,25 @@ import ( "go.mongodb.org/mongo-driver/v2/mongo/options" ) +// Defines a Restaurant struct as a model for documents in the "restaurants" collection +type Restaurant struct { + ID bson.ObjectID `bson:"_id"` + Name string `bson:"name"` + Cuisine string `bson:"cuisine"` + AverageRating float64 `bson:"avg_rating,omitempty"` +} + +// Create a filter struct to specify the documents to update +type UpdateManyRestaurantFilter struct { + Cuisine string `bson:"cuisine"` + Borough string `bson:"borough"` +} + +// Defines a RestaurantUpdate struct to specify the fields to update +type RestaurantUpdateMany struct { + AverageRating float64 `bson:"avg_rating"` +} + func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") @@ -33,15 +52,17 @@ func main() { } }() - // begin updatemany - coll := client.Database("sample_airbnb").Collection("listingsAndReviews") - filter := bson.D{{"address.market", "Sydney"}} + coll := client.Database("sample_restaurants").Collection("restaurants") + filter := UpdateManyRestaurantFilter{ + Cuisine: "Pizza", + Borough: "Brooklyn", + } - // Creates instructions to update the values of the "price" field - update := bson.D{{"$mul", bson.D{{"price", 1.15}}}} + // Creates instructions to update the values of the "AverageRating" field + update := bson.D{{"$set", RestaurantUpdateMany{AverageRating: 4.5}}} - // Updates documents in which the value of the "address.market" - // field is "Sydney" + // Updates documents in which the value of the "Cuisine" + // field is "Pizza" result, err := coll.UpdateMany(context.TODO(), filter, update) if err != nil { panic(err) @@ -49,8 +70,5 @@ func main() { // Prints the number of updated documents fmt.Printf("Documents updated: %v\n", result.ModifiedCount) - // end updatemany - // When you run this file for the first time, it should print: - // Number of documents replaced: 609 } diff --git a/source/includes/usage-examples/code-snippets/updateManyBson.go b/source/includes/usage-examples/code-snippets/updateManyBson.go new file mode 100644 index 00000000..3c52b142 --- /dev/null +++ b/source/includes/usage-examples/code-snippets/updateManyBson.go @@ -0,0 +1,51 @@ +// Updates documents that match a query filter by using the Go driver +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") + filter := bson.D{{"cuisine", "Pizza"}, {"borough", "Brooklyn"}} + + // Creates instructions to update the values of the "avg_rating" field + update := bson.D{{"$set", bson.D{{"avg_rating", 4.5}}}} + + // Updates documents in which the value of the "cuisine" field is "Pizza" + // and the value of the "borough" field is "Brooklyn" + result, err := coll.UpdateMany(context.TODO(), filter, update) + if err != nil { + panic(err) + } + + // Prints the number of updated documents + fmt.Printf("Documents updated: %v\n", result.ModifiedCount) +} diff --git a/source/includes/usage-examples/code-snippets/updateOne.go b/source/includes/usage-examples/code-snippets/updateOne.go index 5e84e294..9860d365 100644 --- a/source/includes/usage-examples/code-snippets/updateOne.go +++ b/source/includes/usage-examples/code-snippets/updateOne.go @@ -13,6 +13,23 @@ import ( "go.mongodb.org/mongo-driver/v2/mongo/options" ) +// Defines a Restaurant struct as a model for documents in the "restaurants" collection +type Restaurant struct { + ID bson.ObjectID `bson:"_id"` + Name string `bson:"name"` + AverageRating float64 `bson:"avg_rating,omitempty"` +} + +// Create a filter struct to specify the document to update +type UpdateRestaurantFilter struct { + ID bson.ObjectID `bson:"_id"` +} + +// Defines a RestaurantUpdate struct to specify the fields to update +type RestaurantUpdate struct { + AverageRating float64 `bson:"avg_rating"` +} + func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") @@ -33,24 +50,20 @@ func main() { } }() - // begin updateone coll := client.Database("sample_restaurants").Collection("restaurants") - id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f42a7a") - filter := bson.D{{"_id", id}} + + id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f4292b") + filter := UpdateRestaurantFilter{ID: id} // Creates instructions to add the "avg_rating" field to documents - update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}} + update := bson.D{{"$set", RestaurantUpdate{AverageRating: 4.4}}} // Updates the first document that has the specified "_id" value result, err := coll.UpdateOne(context.TODO(), filter, update) if err != nil { panic(err) } - // end updateone // Prints the number of updated documents fmt.Printf("Documents updated: %v\n", result.ModifiedCount) - - // When you run this file for the first time, it should print: - // Number of documents replaced: 1 } diff --git a/source/includes/usage-examples/code-snippets/updateOneBson.go b/source/includes/usage-examples/code-snippets/updateOneBson.go new file mode 100644 index 00000000..16315ce3 --- /dev/null +++ b/source/includes/usage-examples/code-snippets/updateOneBson.go @@ -0,0 +1,51 @@ +// Updates the first document that matches a query filter by using the Go driver +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") + id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f42a7a") + filter := bson.D{{"_id", id}} + + // Creates instructions to add the "avg_rating" field to documents + update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}} + + // Updates the first document that has the specified "_id" value + result, err := coll.UpdateOne(context.TODO(), filter, update) + if err != nil { + panic(err) + } + + // Prints the number of updated documents + fmt.Printf("Documents updated: %v\n", result.ModifiedCount) +}