|
| 1 | +================== |
| 2 | +Replace a Document |
| 3 | +================== |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +You can replace a single document using the `replaceOne() |
| 8 | +<https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#replaceOne>`_ |
| 9 | +method. ``replaceOne()`` accepts a query document and a replacement |
| 10 | +document, and fully replaces the first document that matches the query |
| 11 | +with the provided replacement document. All fields and values in the |
| 12 | +original document are removed with the exception of the ``_id`` value, |
| 13 | +which remains the same unless you explicitly specify a new value for |
| 14 | +``_id`` in the replacement document. |
| 15 | + |
| 16 | +You can specify additional options, such as ``upsert``, using the |
| 17 | +optional ``options`` parameter. Configuring the ``upsert`` field to |
| 18 | +``true`` in the options object causes the operation to insert a new |
| 19 | +document if no document matches the query. |
| 20 | + |
| 21 | +The ``replaceOne()`` method returns a `Promise |
| 22 | +<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>`_ |
| 23 | +that resolves to an `updateWriteOpResult |
| 24 | +<https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#~updateWriteOpResult>`_ |
| 25 | +object. You can use the ``modifiedCount`` field of this |
| 26 | +object to determine whether or not a document was modified. If the |
| 27 | +operation was configured to upsert a document, the ``upsertedCount`` |
| 28 | +field indicates the number of newly inserted documents. Use the |
| 29 | +``upsertedId._id`` field if you need a unique identifier for an upserted |
| 30 | +document. |
| 31 | + |
| 32 | +The ``replaceOne()`` method will throw an exception if an error occurs |
| 33 | +during execution. For example, if you specify a value that violates a |
| 34 | +unique index rule, ``replaceOne()`` throws a ``duplicate key error``. |
| 35 | + |
| 36 | +.. note:: |
| 37 | + |
| 38 | + If your application requires the document after updating, |
| 39 | + use the `collection.findOneAndReplace() |
| 40 | + <https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#findOneAndReplace>`_ |
| 41 | + method which has a similar interface to ``replaceOne()``. |
| 42 | + You can configure ``findOneAndReplace()`` to return either the |
| 43 | + original matched document or the replacement document. |
| 44 | + |
| 45 | +.. literalinclude:: /code-snippets/usage-examples/replaceOne.js |
| 46 | + :language: javascript |
| 47 | + :linenos: |
0 commit comments