Replace a Document

Info With Circle IconCreated with Sketch.Note

If you specify a callback method, replaceOne() returns nothing. If you not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

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.

Info With Circle IconCreated with Sketch.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.

Info With Circle IconCreated with Sketch.Note

This example connects to an instance of MongoDB using a connection string. To learn more about connecting to your MongoDB instance, see the connection guide.

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