diff --git a/source/crud/update/replace.txt b/source/crud/update/replace.txt index 3b65a7a3..c198d554 100644 --- a/source/crud/update/replace.txt +++ b/source/crud/update/replace.txt @@ -120,6 +120,44 @@ and the immutable ``_id`` field as follows: "quantity" : 107 } +Replace One Document Example: Full File +--------------------------------------- + +.. include:: /includes/usage-examples/example-intro.rst + +This example performs the following actions on the ``restaurants`` +collection: + +- Matches a document in which the value of ``name`` is ``"Rizzo's Fine Pizza"`` +- Replaces the matched document with a new document + +.. io-code-block:: + :copyable: true + + .. input:: /includes/usage-examples/code-snippets/replace.go + :language: go + :dedent: + + .. output:: + :language: none + :visible: false + + Number of documents replaced: 1 + +Expected Result +~~~~~~~~~~~~~~~ + +After you run the full example, you can find the following replaced document +in the ``restaurants`` collection: + +.. code-block:: none + + { + "_id" : ObjectId("..."), + "name" : "Rizzo's Pizza", + "cuisine" : "Pizza/American" + } + API Documentation ----------------- diff --git a/source/includes/usage-examples/code-snippets/replace.go b/source/includes/usage-examples/code-snippets/replace.go index 84328efe..5525cb94 100644 --- a/source/includes/usage-examples/code-snippets/replace.go +++ b/source/includes/usage-examples/code-snippets/replace.go @@ -13,7 +13,6 @@ import ( "go.mongodb.org/mongo-driver/v2/mongo/options" ) -// start-restaurant-struct type Restaurant struct { Name string RestaurantId string `bson:"restaurant_id,omitempty"` @@ -23,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,23 +42,21 @@ func main() { } }() - // begin replace coll := client.Database("sample_restaurants").Collection("restaurants") - filter := bson.D{{"name", "Madame Vo"}} + filter := bson.D{{"name", "Rizzo's Fine Pizza"}} // Creates a new document containing "Name" and "Cuisine" fields - replacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"} + replacement := Restaurant{Name: "Rizzo's Pizza", Cuisine: "Pizza/American"} // Replaces the first document that matches the filter with a new document result, err := coll.ReplaceOne(context.TODO(), filter, replacement) if err != nil { panic(err) } - // end replace // Prints the number of modified documents if result.MatchedCount != 0 { - fmt.Println("Number of documents replaced: %d\n", result.ModifiedCount) + fmt.Println("Number of documents replaced:", result.ModifiedCount) } // When you run this file for the first time, it should print: