Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
38 changes: 38 additions & 0 deletions source/crud/update/replace.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------

Expand Down
11 changes: 3 additions & 8 deletions source/includes/usage-examples/code-snippets/replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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")
Expand All @@ -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:
Expand Down
Loading