Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Update a Document

Note

If you specify a callback method, updateOne() returns nothing. If you do 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 see the API documentation for information on the result object.

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 additional 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 additional 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.

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

1 document(s) matched the filter, updated 1 document(s)
←  Update & Replace OperationsUpdate Multiple Documents →