|
| 1 | +================= |
| 2 | +Change a Document |
| 3 | +================= |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +Overview |
| 14 | +-------- |
| 15 | + |
| 16 | +In this guide, you can learn how to change documents in MongoDB using |
| 17 | +**update** and **replace** operations. |
| 18 | + |
| 19 | +Update operations change the fields that you specify while leaving other |
| 20 | +fields and values unchanged. Replace operations remove all existing fields |
| 21 | +except for ``_id`` in a document and substitute the deleted fields with |
| 22 | +the new fields and values you specify. |
| 23 | + |
| 24 | +In MongoDB, all methods to change documents follow the same pattern: |
| 25 | + |
| 26 | +.. figure:: /includes/figures/change_diagram.png |
| 27 | + :alt: Change method signature |
| 28 | + |
| 29 | +.. note:: Placeholder |
| 30 | + |
| 31 | + ``changeX`` is a placeholder and not a real method. |
| 32 | + |
| 33 | +The pattern expects you to: |
| 34 | + |
| 35 | +* Specify a query filter to match one or more documents to change. |
| 36 | +* Specify the field and value changes. |
| 37 | +* Specify options to modify behavior, if needed. |
| 38 | + |
| 39 | +.. driver specific |
| 40 | + |
| 41 | +The driver provides the following methods to change documents: |
| 42 | + |
| 43 | +* ``UpdateByID()`` |
| 44 | +* ``UpdateOne()`` |
| 45 | +* ``UpdateMany()`` |
| 46 | +* ``ReplaceOne()`` |
| 47 | +* ``BulkWrite()`` *(not discussed in this guide)* |
| 48 | +* ``FindOneAndUpdate()`` *(not discussed in this guide)* |
| 49 | +* ``FindOneAndReplace()`` *(not discussed in this guide)* |
| 50 | + |
| 51 | +.. end driver specific |
| 52 | + |
| 53 | +A Note About ``_id`` |
| 54 | +~~~~~~~~~~~~~~~~~~~~ |
| 55 | + |
| 56 | +Each document in a MongoDB collection has a unique and immutable ``_id`` |
| 57 | +field. You cannot use update and replace operations to change the |
| 58 | +``_id`` field. If you attempt to change this field, the update and |
| 59 | +replace methods return a `WriteError <{+godocs+}/mongo#WriteError>`__. |
| 60 | + |
| 61 | +.. _updateDocuments: |
| 62 | + |
| 63 | +Update |
| 64 | +------ |
| 65 | + |
| 66 | +Use either `UpdateOne() <{+godocs+}/mongo#Collection.UpdateOne>`__ or |
| 67 | +`UpdateByID() <{+godocs+}/mongo#Collection.UpdateByID>`__ to update a |
| 68 | +single document. |
| 69 | + |
| 70 | +Use `UpdateMany() <{+godocs+}/mongo#Collection.UpdateMany>`__ to update |
| 71 | +multiple documents. |
| 72 | + |
| 73 | + |
| 74 | +Parameters |
| 75 | +~~~~~~~~~~ |
| 76 | + |
| 77 | +Each method takes an **update document** that includes at least one **update operator**. |
| 78 | +The update operator specifies the type of update to perform. The update |
| 79 | +document also includes the fields and values that describe the change. |
| 80 | +Update documents use the following format: |
| 81 | + |
| 82 | +.. code-block:: go |
| 83 | + |
| 84 | + bson.D{{"<update operator>", bson.D{{"<field>", <value>}, |
| 85 | + {"<field>", <value>}, ... }}, |
| 86 | + {"<update operator>", ... }, ... } |
| 87 | + |
| 88 | +See the MongoDB server manual for a :manual:`complete list of update operators |
| 89 | +and descriptions </reference/operator/update-field/>`. |
| 90 | + |
| 91 | +.. note:: Aggregation Pipelines in Update Operations |
| 92 | + |
| 93 | + If you are using MongoDB Server version 4.2 or later, you can use aggregation |
| 94 | + pipelines made up of a subset of aggregation stages in update operations. For |
| 95 | + more information on the aggregation stages MongoDB supports in |
| 96 | + aggregation pipelines, see our tutorial on performing |
| 97 | + :manual:`updates with aggregation pipelines |
| 98 | + </tutorial/update-documents-with-aggregation-pipeline/>`. |
| 99 | + |
| 100 | +Return Values |
| 101 | +~~~~~~~~~~~~~ |
| 102 | + |
| 103 | +``UpdateOne()``, ``UpdateByID()``, and ``UpdateMany()`` return an |
| 104 | +`UpdateResult <{+godocs+}/mongo#UpdateResult>`__ type that |
| 105 | +contains information about the update operation if the operation is |
| 106 | +successful. The ``UpdateResult`` type contains the following properties: |
| 107 | + |
| 108 | +- ``MatchedCount`` - the number of documents matched by the filter |
| 109 | +- ``ModifiedCount`` - the number of documents modified by the operation |
| 110 | +- ``UpsertedCount`` - the number of documents upserted by the operation |
| 111 | +- ``UpsertedID`` - the ``_id`` field of the upserted document, or nil if |
| 112 | + no upsert was performed |
| 113 | + |
| 114 | +If multiple documents match the query filter passed to ``UpdateOne()``, |
| 115 | +the method selects and updates the first matched document. If no |
| 116 | +documents match the query filter, the update operation will make no |
| 117 | +changes. See our :doc:`upsert guide </fundamentals/crud/write-operations/upsert>` |
| 118 | +to learn how to insert a new document if no documents match the query filter. |
| 119 | + |
| 120 | +Example |
| 121 | +~~~~~~~ |
| 122 | + |
| 123 | +The following document describes an employee: |
| 124 | + |
| 125 | +.. code-block:: json |
| 126 | + :copyable: false |
| 127 | + |
| 128 | + { |
| 129 | + "_id" : 2158, |
| 130 | + "name" : "Mary Shelley", |
| 131 | + "department" : "Marketing", |
| 132 | + "role" : "Marketing Analyst", |
| 133 | + "bonus" : 2500, |
| 134 | + ... |
| 135 | + } |
| 136 | + |
| 137 | +The following example uses the ``UpdateByID()`` method to: |
| 138 | + |
| 139 | +- Match the document where the ``_id`` value is 2158. |
| 140 | +- Set the ``name`` field to "Mary Wollstonecraft Shelley" and the |
| 141 | + ``role`` field to "Marketing Director". |
| 142 | +- Increment the value of the ``bonus`` field by 2000. |
| 143 | + |
| 144 | +.. code-block:: go |
| 145 | + |
| 146 | + filter := bson.D{{"_id", 2158}} |
| 147 | + update := bson.D{{"$set", bson.D{{"name", "Mary Wollstonecraft Shelley"}, |
| 148 | + {"role", "Marketing Director"}}}, {"$inc", bson.D{{"bonus", 2000}}}} |
| 149 | + |
| 150 | + result, err := collection.UpdateOne(context.TODO(), filter, update) |
| 151 | + fmt.Printf("Documents matched: %v\n", result.MatchedCount) |
| 152 | + fmt.Printf("Documents updated: %v\n", result.ModifiedCount) |
| 153 | + |
| 154 | +The expected output of the preceding example is as follows: |
| 155 | + |
| 156 | +.. code-block:: none |
| 157 | + :copyable: false |
| 158 | + |
| 159 | + Documents matched: 1 |
| 160 | + Documents updated: 1 |
| 161 | + |
| 162 | +The following shows the updated document resulting from the preceding update operation: |
| 163 | + |
| 164 | +.. code-block:: json |
| 165 | + :copyable: false |
| 166 | + |
| 167 | + { |
| 168 | + "_id" : 2158, |
| 169 | + "name" : "Mary Wollstonecraft Shelley", |
| 170 | + "department" : "Marketing", |
| 171 | + "role" : "Marketing Director", |
| 172 | + "bonus" : 4500, |
| 173 | + ... |
| 174 | + } |
| 175 | + |
| 176 | +.. _replacementDocument: |
| 177 | + |
| 178 | +Replace |
| 179 | +------- |
| 180 | + |
| 181 | +Use the `ReplaceOne() <{+godocs+}/mongo#Collection.ReplaceOne>`__ method |
| 182 | +to replace a single document. |
| 183 | + |
| 184 | +Parameters |
| 185 | +~~~~~~~~~~ |
| 186 | + |
| 187 | +``ReplaceOne()`` expects a **replacement document**, which is the document |
| 188 | +that you want to take the place of an existing document. Replacement |
| 189 | +documents use the following format: |
| 190 | + |
| 191 | +.. code-block:: go |
| 192 | + |
| 193 | + bson.D{{"<field>", "<value>"}, {"<field>", "<value>"}, ... } |
| 194 | + |
| 195 | +Return Values |
| 196 | +~~~~~~~~~~~~~ |
| 197 | + |
| 198 | +``ReplaceOne()`` returns an `UpdateResult <{+godocs+}/mongo#UpdateResult>`__ type that |
| 199 | +contains information about the replace operation if the operation is |
| 200 | +successful. The ``UpdateResult`` type contains the following properties: |
| 201 | + |
| 202 | +- ``MatchedCount`` - the number of documents matched by the filter |
| 203 | +- ``ModifiedCount`` - the number of documents modified by the operation |
| 204 | +- ``UpsertedCount`` - the number of documents upserted by the operation |
| 205 | +- ``UpsertedID`` - the ``_id`` field of the upserted document, or nil if |
| 206 | + no upsert was performed |
| 207 | + |
| 208 | +If multiple documents match the query filter passed to ``ReplaceOne()``, |
| 209 | +the method selects and replaces the first matched document. Your replace |
| 210 | +operation will fail if no documents match the query filter. See our **<TODO: |
| 211 | +link>** upsert guide to learn how to insert a new document if no |
| 212 | +documents match the query filter. |
| 213 | + |
| 214 | +Example |
| 215 | +~~~~~~~ |
| 216 | + |
| 217 | +The following document describes a kitchen item: |
| 218 | + |
| 219 | +.. code-block:: json |
| 220 | + :copyable: false |
| 221 | + |
| 222 | + { |
| 223 | + "_id" : 2056, |
| 224 | + "item" : "Mug", |
| 225 | + "brand" : "Simply Ceramics", |
| 226 | + "price" : 2.99, |
| 227 | + "material" : "Glass" |
| 228 | + } |
| 229 | + |
| 230 | +The following example uses the ``ReplaceOne()`` method to substitute |
| 231 | +this document with one that contains an ``item`` field with a |
| 232 | +value of "Cup" and a ``quantity`` field with a value of 107: |
| 233 | + |
| 234 | +.. code-block:: go |
| 235 | + |
| 236 | + filter := bson.D{{"_id", 2056}} |
| 237 | + replacement := bson.D{{"item", "Cup"}, {"quantity", 107}} |
| 238 | + |
| 239 | + result, err := collection.ReplaceOne(context.TODO(), filter, replacement) |
| 240 | + fmt.Printf("Documents matched: %v\n", result.MatchedCount) |
| 241 | + fmt.Printf("Documents replaced: %v\n", result.ModifiedCount) |
| 242 | + |
| 243 | +The expected output of the preceding example is as follows: |
| 244 | + |
| 245 | +.. code-block:: none |
| 246 | + :copyable: false |
| 247 | + |
| 248 | + Documents matched: 1 |
| 249 | + Documents replaced: 1 |
| 250 | + |
| 251 | +The replaced document contains the contents of the replacement document |
| 252 | +and the immutable ``_id`` field as follows: |
| 253 | + |
| 254 | +.. code-block:: json |
| 255 | + :copyable: false |
| 256 | + |
| 257 | + { |
| 258 | + "_id" : 2056, |
| 259 | + "item" : "Cup", |
| 260 | + "quantity" : 107 |
| 261 | + } |
0 commit comments