Skip to content

Commit 8fe762a

Browse files
(DOCSP-7605): replace a document (#20)
1 parent 416b830 commit 8fe762a

File tree

4 files changed

+110
-9
lines changed

4 files changed

+110
-9
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// ignored first line
2+
const { MongoClient } = require("mongodb");
3+
4+
// Replace the following with your MongoDB deployment's connection string.
5+
const uri =
6+
"mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority";
7+
8+
const client = new MongoClient(uri);
9+
10+
async function run() {
11+
try {
12+
await client.connect();
13+
14+
const database = client.db("sample_mflix");
15+
const collection = database.collection("movies");
16+
17+
// create a query for a movie to update
18+
const query = { title: "Blacksmith Scene" };
19+
const options = {
20+
// create a document if no documents match the query
21+
upsert: true,
22+
};
23+
// create a new document that will be used to replace the existing document
24+
const replacement = {
25+
title: "Sandcastles in the Sand",
26+
plot:
27+
"Robin Sparkles mourns for a relationship with a mall rat at an idyllic beach.",
28+
};
29+
30+
const result = await collection.replaceOne(query, replacement, options);
31+
32+
if (result.modifiedCount === 0 && result.upsertedCount === 0) {
33+
console.log("No changes made to the collection.");
34+
} else {
35+
if (result.matchedCount === 1) {
36+
console.log("Matched " + result.matchedCount + " documents.");
37+
}
38+
if (result.modifiedCount === 1) {
39+
console.log("Updated one document.");
40+
}
41+
if (result.upsertedCount === 1) {
42+
console.log(
43+
"Inserted one new document with an _id of " + result.upsertedId._id,
44+
);
45+
}
46+
}
47+
} finally {
48+
await client.close();
49+
}
50+
}
51+
run().catch(console.dir);

source/usage-examples.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Usage Examples
1313
:doc:`findOne </usage-examples/findOne>`
1414
:doc:`insertMany </usage-examples/insertMany>`
1515
:doc:`updateOne</usage-examples/updateOne>`
16+
:doc:`replaceOne</usage-examples/replaceOne>`
1617
:doc:`distinct</usage-examples/distinct>`
1718

1819
.. toctree::
@@ -28,4 +29,5 @@ Usage Examples
2829
/usage-examples/findOneAndUpdate
2930
/usage-examples/insertMany
3031
/usage-examples/updateOne
32+
/usage-examples/replaceOne
3133
/usage-examples/distinct
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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:

source/usage-examples/updateOne.txt

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,24 @@ You can update a single document using the `updateOne()
99
method. ``updateOne()`` accepts a filter document, and updates the first
1010
document that matches the filter using a provided update document. The
1111
update document requires an :manual:`Update
12-
Operator<reference/operator/update/#update-operators`_ to modify a field in a document.
12+
Operator</reference/operator/update/#update-operators>`
13+
to modify a field in a document.
1314

1415
Create an `Object
1516
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object>`_
16-
to specify additional options. Set the ``upsert`` option to ``true`` to create a new
17-
document if no documents match the filter.
17+
to specify additional options. Set the ``upsert`` option to ``true`` to
18+
create a new document if no documents match the filter.
1819

1920
The ``updateOne()`` method returns a `Promise
2021
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>`_
2122
that resolves to an object. The ``modifiedCount`` field of this object
22-
has a value of ``0`` if no documents were updated, and a value of ``1`` if a
23-
document was updated.
23+
has a value of ``0`` if no documents were updated, and a value of ``1``
24+
if a document was updated.
2425

25-
Specifying incorrect parameters for your ``updateOne()`` operation can cause
26-
problems. Attempting to modify the immutable field ``_id`` will result
27-
in an error. Additionally, trying to update a field to value that would
28-
violate unique index rules will throw a ``duplicate key error``.
26+
Specifying incorrect parameters for your ``updateOne()`` operation can
27+
cause problems. Attempting to modify the immutable field ``_id`` will
28+
result in an error. Additionally, trying to update a field to value that
29+
would violate unique index rules will throw a ``duplicate key error``.
2930

3031
.. literalinclude:: /code-snippets/usage-examples/updateOne.js
3132
:language: javascript

0 commit comments

Comments
 (0)