Docs Menu
Docs Home
/ / /
Node.js Driver
/ /

Replace Documents

On this page

  • Overview
  • Replace a Document
  • Example
  • replaceOne() Example: Full File
  • API Documentation

In this guide, you can learn how to use Node.js driver to perform a replace operation on a document in a MongoDB collection. A replace operation performs differently than an update operation. An update operation modifies only the specified fields in a target document. A replace operation removes all fields in the target document and replaces them with new ones.

To perform a replacement operation, create a replacement document that consists of the fields and values that you want to use in your replace operation. Replacement documents use the following format:

{
<field>: {
<value>
},
<field>: {
...
}
}

Replacement documents are the documents that you want to take the place of existing documents that match the query filters.

You can specify more 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.

Consider a document in the myDB.items collection with fields describing an item for sale, its price, and the quantity available:

{
_id: 501,
item: "3-wick beeswax candle",
price: 18.99,
quantity: 10,
}

Suppose you wanted to replace this document with one that contains a description for an entirely different item. Your replacement operation might resemble the following:

const myDB = client.db("myDB");
const myColl = myDB.collection("items");
const filter = { _id: 501 };
// replace the matched document with the replacement document
const replacementDocument = {
item: "Vintage silver flatware set",
price: 79.15,
quantity: 1,
};
const result = await myColl.replaceOne(filter, replacementDocument);

The replaced document contains the contents of the replacement document and the immutable _id field as follows:

{
_id: 501,
item: "Vintage silver flatware set",
price: 79.15,
quantity: 1,
}

If a replace operation fails to match any documents in a collection, it does not make any changes. Replace operations can be configured to perform an upsert which attempts to perform the replacement, but if no documents are matched, it inserts a new document with the specified fields and values.

You cannot modify the _id field of a document nor change a field to a value that violates a unique index constraint. See the MongoDB Server manual for more information on unique indexes.

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following code is a complete, standalone file that performs a replace one operation:

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a query for documents where the title contains "The Cat from"
16 const query = { title: { $regex: "The Cat from" } };
17
18 // Create the document that will replace the existing document
19 const replacement = {
20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
21 };
22
23 // Execute the replace operation
24 const result = await movies.replaceOne(query, replacement);
25
26 // Print the result
27 console.log(`Modified ${result.modifiedCount} document(s)`);
28 } finally {
29 await client.close();
30 }
31}
32run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10}
11
12async function run() {
13 try {
14 const database = client.db("sample_mflix");
15 const movies = database.collection<Movie>("movies");
16
17 const result = await movies.replaceOne(
18 { title: { $regex: "The Cat from" } },
19 {
20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
21 }
22 );
23 console.log(`Modified ${result.modifiedCount} document(s)`);
24 } finally {
25 await client.close();
26 }
27}
28run().catch(console.dir);

Running the preceding example results in the following output:

Modified 1 document(s)

To learn more about any of the types or methods discussed in this guide, see the following API documentation:

Back

Modify Documents