Skip to content

Commit d72f411

Browse files
committed
Merge branch 'comp-cov' into docsp-51819-standardizeDeleteUsageEx
2 parents fbe3d9f + 8222636 commit d72f411

File tree

6 files changed

+248
-33
lines changed

6 files changed

+248
-33
lines changed

source/crud/update.txt

Lines changed: 87 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -204,28 +204,99 @@ The following shows the updated document resulting from the preceding update ope
204204
...
205205
}
206206

207-
UpdateMany() Example
208-
--------------------
207+
UpdateOne() Example: Full File
208+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
209209

210-
The following example uses the ``listingsAndReviews`` collection in the
211-
``sample_airbnb`` dataset from the :atlas:`Atlas sample datasets </sample-data/sample-airbnb>`.
210+
.. include:: /includes/usage-examples/example-intro.rst
211+
212+
The following example is a fully runnable file that finds and updates an
213+
existing document in the ``restaurants`` collection. Select the
214+
:guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:
215+
216+
.. tabs::
217+
218+
.. tab:: Struct
219+
:tabid: structExample
220+
221+
The following code uses a struct to define the filter and update a document in the ``restuarants`` collection:
222+
223+
.. io-code-block::
224+
:copyable: true
225+
226+
.. input:: /includes/usage-examples/code-snippets/updateOne.go
227+
:language: go
228+
:dedent:
229+
230+
.. output::
231+
:language: none
232+
:visible: false
233+
234+
Documents updated: 1
235+
236+
.. tab:: bson.D
237+
:tabid: bsonDExample
238+
239+
The following code uses a ``bson.D`` type to define the filter and update a document in the ``restuarants`` collection:
240+
241+
.. io-code-block::
242+
:copyable: true
243+
244+
.. input:: /includes/usage-examples/code-snippets/updateOneBson.go
245+
:language: go
246+
:dedent:
247+
248+
.. output::
249+
:language: none
250+
:visible: false
251+
252+
Documents updated: 1
253+
254+
UpdateMany() Example: Full File
255+
-------------------------------
256+
257+
.. include:: /includes/usage-examples/example-intro.rst
258+
259+
The following example is a fully runnable file that finds and updates multiple
260+
existing documents in the ``restaurants`` collection. Select the
261+
:guilabel:`Struct` or :guilabel:`bson.D` tab to see the corresponding code:
262+
263+
.. tabs::
264+
265+
.. tab:: Struct
266+
:tabid: structExample
267+
268+
The following code uses a struct to define the filter and update multiple documents in the ``restuarants`` collection:
269+
270+
.. io-code-block::
271+
:copyable: true
272+
273+
.. input:: /includes/usage-examples/code-snippets/updateMany.go
274+
:language: go
275+
:dedent:
276+
277+
.. output::
278+
:language: none
279+
:visible: false
280+
281+
Documents updated: 296
282+
283+
.. tab:: bson.D
284+
:tabid: bsonDExample
212285

213-
The following example uses the ``UpdateMany()`` method to:
286+
The following code uses a ``bson.D`` type to define the filter and update multiple documents in the ``restuarants`` collection:
214287

215-
- Match documents in which the value of the ``address.market`` field is ``"Sydney"``.
216-
- Multiply the ``price`` value in the matched documents by ``1.15``
288+
.. io-code-block::
289+
:copyable: true
217290

218-
.. literalinclude:: /includes/usage-examples/code-snippets/updateMany.go
219-
:start-after: begin updatemany
220-
:end-before: end updatemany
221-
:emphasize-lines: 9
222-
:language: go
223-
:copyable:
224-
:dedent:
291+
.. input:: /includes/usage-examples/code-snippets/updateManyBson.go
292+
:language: go
293+
:dedent:
225294

226-
The update operation updates ``609`` documents.
295+
.. output::
296+
:language: none
297+
:visible: false
227298

228-
To learn more about how to retrieve multiple documents, see :ref:`golang-find-example`.
299+
Documents updated: 296
229300

230301
Additional Information
231302
----------------------

source/includes/usage-examples/code-snippets/insertOneBsonD.go

Whitespace-only changes.

source/includes/usage-examples/code-snippets/updateMany.go

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,25 @@ import (
1313
"go.mongodb.org/mongo-driver/v2/mongo/options"
1414
)
1515

16+
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
17+
type Restaurant struct {
18+
ID bson.ObjectID `bson:"_id"`
19+
Name string `bson:"name"`
20+
Cuisine string `bson:"cuisine"`
21+
AverageRating float64 `bson:"avg_rating,omitempty"`
22+
}
23+
24+
// Create a filter struct to specify the documents to update
25+
type UpdateManyRestaurantFilter struct {
26+
Cuisine string `bson:"cuisine"`
27+
Borough string `bson:"borough"`
28+
}
29+
30+
// Defines a RestaurantUpdate struct to specify the fields to update
31+
type RestaurantUpdateMany struct {
32+
AverageRating float64 `bson:"avg_rating"`
33+
}
34+
1635
func main() {
1736
if err := godotenv.Load(); err != nil {
1837
log.Println("No .env file found")
@@ -33,24 +52,25 @@ func main() {
3352
}
3453
}()
3554

36-
// begin updatemany
37-
coll := client.Database("sample_airbnb").Collection("listingsAndReviews")
38-
filter := bson.D{{"address.market", "Sydney"}}
55+
coll := client.Database("sample_restaurants").Collection("restaurants")
56+
filter := UpdateManyRestaurantFilter{
57+
Cuisine: "Pizza",
58+
Borough: "Brooklyn",
59+
}
3960

40-
// Creates instructions to update the values of the "price" field
41-
update := bson.D{{"$mul", bson.D{{"price", 1.15}}}}
61+
// Creates instructions to update the values of the "AverageRating" field
62+
update := bson.D{{"$set", RestaurantUpdateMany{AverageRating: 4.5}}}
4263

43-
// Updates documents in which the value of the "address.market"
44-
// field is "Sydney"
64+
// Updates documents in which the value of the "Cuisine"
65+
// field is "Pizza"
4566
result, err := coll.UpdateMany(context.TODO(), filter, update)
4667
if err != nil {
4768
panic(err)
4869
}
4970

5071
// Prints the number of updated documents
5172
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
52-
// end updatemany
5373

54-
// When you run this file for the first time, it should print:
55-
// Number of documents replaced: 609
74+
// When you run this file for the first time, it should print output similar to the following:
75+
// Documents updated: 296
5676
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Updates documents that match a query filter by using the Go driver
2+
package main
3+
4+
import (
5+
"context"
6+
"fmt"
7+
"log"
8+
"os"
9+
10+
"github.com/joho/godotenv"
11+
"go.mongodb.org/mongo-driver/v2/bson"
12+
"go.mongodb.org/mongo-driver/v2/mongo"
13+
"go.mongodb.org/mongo-driver/v2/mongo/options"
14+
)
15+
16+
func main() {
17+
if err := godotenv.Load(); err != nil {
18+
log.Println("No .env file found")
19+
}
20+
21+
var uri string
22+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
23+
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")
24+
}
25+
26+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
27+
if err != nil {
28+
panic(err)
29+
}
30+
defer func() {
31+
if err = client.Disconnect(context.TODO()); err != nil {
32+
panic(err)
33+
}
34+
}()
35+
36+
coll := client.Database("sample_restaurants").Collection("restaurants")
37+
filter := bson.D{{"cuisine", "Pizza"}, {"borough", "Brooklyn"}}
38+
39+
// Creates instructions to update the values of the "avg_rating" field
40+
update := bson.D{{"$set", bson.D{{"avg_rating", 4.5}}}}
41+
42+
// Updates documents in which the value of the "cuisine" field is "Pizza"
43+
// and the value of the "borough" field is "Brooklyn"
44+
result, err := coll.UpdateMany(context.TODO(), filter, update)
45+
if err != nil {
46+
panic(err)
47+
}
48+
49+
// Prints the number of updated documents
50+
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
51+
52+
// When you run this file for the first time, it should print output similar to the following:
53+
// Documents updated: 296
54+
}

source/includes/usage-examples/code-snippets/updateOne.go

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,23 @@ import (
1313
"go.mongodb.org/mongo-driver/v2/mongo/options"
1414
)
1515

16+
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
17+
type Restaurant struct {
18+
ID bson.ObjectID `bson:"_id"`
19+
Name string `bson:"name"`
20+
AverageRating float64 `bson:"avg_rating,omitempty"`
21+
}
22+
23+
// Create a filter struct to specify the document to update
24+
type UpdateRestaurantFilter struct {
25+
ID bson.ObjectID `bson:"_id"`
26+
}
27+
28+
// Defines a RestaurantUpdate struct to specify the fields to update
29+
type RestaurantUpdate struct {
30+
AverageRating float64 `bson:"avg_rating"`
31+
}
32+
1633
func main() {
1734
if err := godotenv.Load(); err != nil {
1835
log.Println("No .env file found")
@@ -33,24 +50,23 @@ func main() {
3350
}
3451
}()
3552

36-
// begin updateone
3753
coll := client.Database("sample_restaurants").Collection("restaurants")
38-
id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f42a7a")
39-
filter := bson.D{{"_id", id}}
54+
55+
id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f4292b")
56+
filter := UpdateRestaurantFilter{ID: id}
4057

4158
// Creates instructions to add the "avg_rating" field to documents
42-
update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}}
59+
update := bson.D{{"$set", RestaurantUpdate{AverageRating: 4.4}}}
4360

4461
// Updates the first document that has the specified "_id" value
4562
result, err := coll.UpdateOne(context.TODO(), filter, update)
4663
if err != nil {
4764
panic(err)
4865
}
49-
// end updateone
5066

5167
// Prints the number of updated documents
5268
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
5369

54-
// When you run this file for the first time, it should print:
55-
// Number of documents replaced: 1
70+
// When you run this file for the first time, it should print output similar to the following:
71+
// Documents updated: 1
5672
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Updates the first document that matches a query filter by using the Go driver
2+
package main
3+
4+
import (
5+
"context"
6+
"fmt"
7+
"log"
8+
"os"
9+
10+
"github.com/joho/godotenv"
11+
"go.mongodb.org/mongo-driver/v2/bson"
12+
"go.mongodb.org/mongo-driver/v2/mongo"
13+
"go.mongodb.org/mongo-driver/v2/mongo/options"
14+
)
15+
16+
func main() {
17+
if err := godotenv.Load(); err != nil {
18+
log.Println("No .env file found")
19+
}
20+
21+
var uri string
22+
if uri = os.Getenv("MONGODB_URI"); uri == "" {
23+
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")
24+
}
25+
26+
client, err := mongo.Connect(options.Client().ApplyURI(uri))
27+
if err != nil {
28+
panic(err)
29+
}
30+
defer func() {
31+
if err = client.Disconnect(context.TODO()); err != nil {
32+
panic(err)
33+
}
34+
}()
35+
36+
coll := client.Database("sample_restaurants").Collection("restaurants")
37+
id, _ := bson.ObjectIDFromHex("5eb3d668b31de5d588f42a7a")
38+
filter := bson.D{{"_id", id}}
39+
40+
// Creates instructions to add the "avg_rating" field to documents
41+
update := bson.D{{"$set", bson.D{{"avg_rating", 4.4}}}}
42+
43+
// Updates the first document that has the specified "_id" value
44+
result, err := coll.UpdateOne(context.TODO(), filter, update)
45+
if err != nil {
46+
panic(err)
47+
}
48+
49+
// Prints the number of updated documents
50+
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
51+
52+
// When you run this file for the first time, it should print output similar to the following:
53+
// Documents updated: 1
54+
}

0 commit comments

Comments
 (0)