-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathmodify.txt
335 lines (240 loc) · 9.24 KB
/
modify.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
.. _golang-change-document:
================
Modify Documents
================
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: code example, write operation, change data
:description: Learn how to modify MongoDB documents using update and replace operations, including methods like updateOne(), updateMany(), and replaceOne().
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to modify documents in MongoDB using
**update** and **replace** operations.
Update operations change the fields that you specify while leaving other
fields and values unchanged. Replace operations remove all existing fields
except for ``_id`` in a document and substitute the deleted fields with
the new fields and values you specify.
In MongoDB, all methods to modify documents follow the same pattern:
.. figure:: /includes/figures/change_diagram.png
:alt: Change method signature
.. note:: Placeholder
``changeX`` is a placeholder and not a real method.
The pattern expects you to:
* Specify a query filter to match one or more documents to modify.
* Specify the field and value changes.
* Specify options, if you must modify the method behavior.
The driver provides the following methods to modify documents:
* ``UpdateByID()``
* ``UpdateOne()``
* ``UpdateMany()``
* ``ReplaceOne()``
* ``BulkWrite()`` *(not discussed in this guide)*
* ``FindOneAndUpdate()`` *(not discussed in this guide)*
* ``FindOneAndReplace()`` *(not discussed in this guide)*
A Note About ``_id``
~~~~~~~~~~~~~~~~~~~~
Each document in a MongoDB collection has a unique and immutable ``_id``
field. You cannot use update and replace operations to change the
``_id`` field. If you attempt to change this field, the update and
replace methods return a ``WriteError``.
.. _golang-update-documents:
Update
------
Use the ``UpdateOne()`` or ``UpdateByID()`` method to update a single
document.
Use the ``UpdateMany()`` method to update multiple documents.
.. _golang-update-document:
Parameters
~~~~~~~~~~
Each method takes an **update document** that includes at least one **update operator**.
The update operator specifies the type of update to perform. The update
document also includes the fields and values that describe the change.
Update documents use the following format:
.. code-block:: go
bson.D{{"<update operator>", bson.D{{"<field>", <value>},
{"<field>", <value>}, ... }},
{"<update operator>", ... }, ... }
See the MongoDB server manual for a :manual:`complete list of update operators
and descriptions </reference/operator/update-field/>`.
.. tip::
``UpdateOne()`` updates the first document that matches the query filter
you provide. To ensure that you update the correct document, you can use the ``sort``
option to specify the order in which the operation finds documents. To learn more,
see the `UpdateOneOptions <{+api+}/mongo/options#UpdateOneOptions>`__ API documentation.
.. note:: Aggregation Pipelines in Update Operations
If you are using MongoDB Server version 4.2 or later, you can use aggregation
pipelines made up of a subset of aggregation stages in update operations. To learn more about
the aggregation stages MongoDB supports in
aggregation pipelines, see our tutorial on performing
:manual:`updates with aggregation pipelines
</tutorial/update-documents-with-aggregation-pipeline/>`.
Return Values
~~~~~~~~~~~~~
``UpdateOne()``, ``UpdateByID()``, and ``UpdateMany()`` return an
``UpdateResult`` type that contains information about the update
operation if the operation is successful. The ``UpdateResult`` type
contains the following properties:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Property
- Description
* - ``MatchedCount``
- The number of documents matched by the filter
* - ``ModifiedCount``
- The number of documents modified by the operation
* - ``UpsertedCount``
- The number of documents upserted by the operation
* - ``UpsertedID``
- The ``_id`` of the upserted document, or ``nil`` if there is none
If multiple documents match the query filter passed to ``UpdateOne()``,
the method selects and updates the first matched document. If no
documents match the query filter, the update operation makes no
changes.
See our :ref:`upsert guide <golang-upsert-guide>`
to learn how to insert a new document if no documents match the query filter.
Example
```````
The following document describes an employee:
.. code-block:: json
:copyable: false
{
"_id" : 2158,
"name" : "Mary Shelley",
"department" : "Marketing",
"role" : "Marketing Analyst",
"bonus" : 2500,
...
}
The following example uses the ``UpdateByID()`` method to:
- Match the document where the ``_id`` value is 2158.
- Set the ``name`` field to "Mary Wollstonecraft Shelley" and the
``role`` field to "Marketing Director".
- Increment the value of the ``bonus`` field by 2000.
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"_id", 2158}}
update := bson.D{{"$set", bson.D{{"name", "Mary Wollstonecraft Shelley"},
{"role", "Marketing Director"}}}, {"$inc", bson.D{{"bonus", 2000}}}}
result, err := collection.UpdateOne(context.TODO(), filter, update)
fmt.Printf("Documents matched: %v\n", result.MatchedCount)
fmt.Printf("Documents updated: %v\n", result.ModifiedCount)
.. output::
:language: none
:visible: false
Documents matched: 1
Documents updated: 1
The following shows the updated document resulting from the preceding update operation:
.. code-block:: json
:copyable: false
{
"_id" : 2158,
"name" : "Mary Wollstonecraft Shelley",
"department" : "Marketing",
"role" : "Marketing Director",
"bonus" : 4500,
...
}
.. _golang-replacement-document:
Replace
-------
Use the ``ReplaceOne()`` method to replace a single document.
Parameters
~~~~~~~~~~
``ReplaceOne()`` expects a **replacement document**, which is the document
that you want to take the place of an existing document. Replacement
documents use the following format:
.. code-block:: go
bson.D{{"<field>", "<value>"}, {"<field>", "<value>"}, ... }
Return Values
~~~~~~~~~~~~~
``ReplaceOne()`` returns an ``UpdateResult`` type that
contains information about the replace operation if the operation is
successful. The ``UpdateResult`` type contains the following properties:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Property
- Description
* - ``MatchedCount``
- The number of documents matched by the filter
* - ``ModifiedCount``
- The number of documents modified by the operation
* - ``UpsertedCount``
- The number of documents upserted by the operation
* - ``UpsertedID``
- The ``_id`` of the upserted document, or ``nil`` if there is none
If multiple documents match the query filter passed to ``ReplaceOne()``,
the method selects and replaces the first matched document. Your replace
operation fails if no documents match the query filter.
Example
```````
The following document describes a kitchen item:
.. code-block:: json
:copyable: false
{
"_id" : 2056,
"item" : "Mug",
"brand" : "Simply Ceramics",
"price" : 2.99,
"material" : "Glass"
}
The following example uses the ``ReplaceOne()`` method to substitute
this document with one that contains an ``item`` field with a
value of "Cup" and a ``quantity`` field with a value of 107:
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"_id", 2056}}
replacement := bson.D{{"item", "Cup"}, {"quantity", 107}}
result, err := collection.ReplaceOne(context.TODO(), filter, replacement)
fmt.Printf("Documents matched: %v\n", result.MatchedCount)
fmt.Printf("Documents replaced: %v\n", result.ModifiedCount)
.. output::
:language: none
:visible: false
Documents matched: 1
Documents replaced: 1
The replaced document contains the contents of the replacement document
and the immutable ``_id`` field as follows:
.. code-block:: json
:copyable: false
{
"_id" : 2056,
"item" : "Cup",
"quantity" : 107
}
Additional Information
----------------------
For runnable examples of the update and replace operations, see the
following usage examples:
- :ref:`golang-update-one`
- :ref:`golang-update-many`
- :ref:`golang-replace`
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-upsert`
- :ref:`golang-compound-operations`
- :manual:`Update Operators </reference/operator/update/#update-operators>`
To learn more about updating array elements, see :ref:`golang-update-arrays`.
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `WriteError <{+api+}/mongo#WriteError>`__
- `UpdateOne() <{+api+}/mongo#Collection.UpdateOne>`__
- `UpdateByID() <{+api+}/mongo#Collection.UpdateByID>`__
- `UpdateMany() <{+api+}/mongo#Collection.UpdateMany>`__
- `UpdateResult <{+api+}/mongo#UpdateResult>`__
- `ReplaceOne() <{+api+}/mongo#Collection.ReplaceOne>`__