Skip to content

DOCSP-51817 Move update usage examples #540

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

Open
wants to merge 6 commits into
base: comp-cov
Choose a base branch
from
Open
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
103 changes: 87 additions & 16 deletions source/crud/update.txt
Original file line number Diff line number Diff line change
Expand Up @@ -204,28 +204,99 @@ The following shows the updated document resulting from the preceding update ope
...
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

[note for reviewer] I'm thinking of just removing the extra UpdateOne() example and only including the full file. Other comp cov usage example reworks kept the other example but this one seems kind of redundant, lmk what you think!


UpdateMany() Example
--------------------
UpdateOne() Example: Full File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following example uses the ``listingsAndReviews`` collection in the
``sample_airbnb`` dataset from the :atlas:`Atlas sample datasets </sample-data/sample-airbnb>`.
.. 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
----------------------
Expand Down
38 changes: 28 additions & 10 deletions source/includes/usage-examples/code-snippets/updateMany.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -33,24 +52,23 @@ 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)
}

// 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
}
51 changes: 51 additions & 0 deletions source/includes/usage-examples/code-snippets/updateManyBson.go
Original file line number Diff line number Diff line change
@@ -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)
}
29 changes: 21 additions & 8 deletions source/includes/usage-examples/code-snippets/updateOne.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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
}
51 changes: 51 additions & 0 deletions source/includes/usage-examples/code-snippets/updateOneBson.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading