Replace a Document
You can replace a single document using the
collection.replaceOne() method.
replaceOne()
accepts a query document and a replacement document. If
the query matches a document in the collection, it replaces the first
document that matches the query with the provided replacement document.
This operation removes all fields and values in the original document and
replaces them with the fields and values in the replacement document. The
value of the _id
field remains the same unless you explicitly specify
a new value for _id
in the replacement document.
You can specify additional options, such as upsert
, using the
optional options
parameter. If you set the upsert
option field to
true
the method inserts a new document if no document matches the query.
The replaceOne()
method throws an exception if an error occurs
during execution. For example, if you specify a value that violates a
unique index rule, replaceOne()
throws a duplicate key error
.
Note
If your application requires the document after updating,
use the collection.findOneAndReplace()
method which has a similar interface to replaceOne()
.
You can configure findOneAndReplace()
to return either the
original matched document or the replacement document.
Example
Note
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
If you run the preceding example, you should see the following output:
Modified 1 document(s)