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

  • A connection string to your MongoDB deployment.

  • Sample datasets loaded into your cluster.

  • An installed MongoDB Driver.

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:

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
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.