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

Update a Document

You can update a single document using the collection.updateOne() method. The updateOne() method accepts a filter document and an update document. If the query matches documents in the collection, the method applies the updates from the update document to fields and values of them. The update document contains update operators that instruct the method on the changes to make to the matches.

You can specify more query options using the options object passed as the second parameter of the updateOne() method. Set the upsert option to true to create a new document if no documents match the filter. For more information, see the updateOne() API documentation.

updateOne() throws an exception if an error occurs during execution. If you specify a value in your update document for the immutable field _id, the method throws an exception. If your update document contains a value that violates unique index rules, the method throws a duplicate key error exception.

Note

If your application requires the document after updating, consider using the collection.findOneAndUpdate(). method, which has a similar interface to updateOne() but also returns the original or updated document.

The following example uses the $set update operator which specifies update values for document fields. For more information on update operators, see the MongoDB update operator reference documentation.

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.

1// Update a document
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a filter for movies with the title "Random Harvest"
16 const filter = { title: "Random Harvest" };
17
18 /* Set the upsert option to insert a document if no documents match
19 the filter */
20 const options = { upsert: true };
21
22 // Specify the update to set a value for the plot field
23 const updateDoc = {
24 $set: {
25 plot: `A harvest of random numbers, such as: ${Math.random()}`
26 },
27 };
28
29 // Update the first document that matches the filter
30 const result = await movies.updateOne(filter, updateDoc, options);
31
32 // Print the number of matching and modified documents
33 console.log(
34 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
35 );
36 } finally {
37 // Close the connection after the operation completes
38 await client.close();
39 }
40}
41// Run the program and print any thrown errors
42run().catch(console.dir);
1// Update a document
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10// Define the Movie interface
11interface Movie {
12 plot: string;
13 title: string;
14}
15
16async function run() {
17 try {
18 const database = client.db("sample_mflix");
19 const movies = database.collection<Movie>("movies");
20
21 /* Update a document that has the title "Random Harvest" to have a
22 plot field with the specified value */
23 const result = await movies.updateOne(
24 { title: "Random Harvest" },
25 {
26 $set: {
27 plot: `A harvest of random numbers, such as: ${Math.random()}`,
28 },
29 },
30 /* Set the upsert option to insert a document if no documents
31 match the filter */
32 { upsert: true }
33 );
34
35 // Print the number of matching and modified documents
36 console.log(
37 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`
38 );
39 } finally {
40 // Close the connection after the operation completes
41 await client.close();
42 }
43}
44// Run the program and print any thrown errors
45run().catch(console.dir);

If you run the example above, you see the following output:

1 document(s) matched the filter, updated 1 document(s)

Back

Update & Replace Operations