Docs Menu

Docs HomeStart with Guides

Update Data in MongoDB

In this guide, you will update a field in a document.

Time required: 10 minutes

1
2

Switch to the database and collection you wish to work with. In this case you will be using the sample_guides database and comets collection.

3

In the previous guide, you inserted documents into the comets collection. Now, you have a requirement to update those documents. All fields are in metric units except for the radius, which is in imperial.

The following example uses an update document to convert the radius field from the metric system to the imperial system in all documents.

Tip

Conversion

1 mile = 1.60934 kilometers

4

Many write operations in MongoDB return a result object that contains information about the operation.

For update operations, the result object will contain the modified count of documents the driver successfully updated. Here, you access this property and print them.

5

Here is the complete code followed by sample output.

If you have completed this guide, you have updated data in MongoDB.

In the next guide, you will delete documents from MongoDB.

See the following resources for more in-depth information about the concepts presented here:

  • Update Documents

  • Update Methods

What's Next
Delete Data from MongoDB
10 mins

Specify which documents to delete from MongoDB.

Start Guide
Chapter 2
CRUD
  • Add a MongoDB Driver
  • Read Data in MongoDB
  • Read Data from MongoDB With Queries
  • Read Data using Operators and Compound Queries
  • Insert Data into MongoDB
  • Update Data in MongoDB
  • Delete Data from MongoDB
Start with Guides →