Update MongoDB Records: Complete Guide

In MongoDB, you can use the update() method to update a single piece of data. When updating data, you need to specify the update criteria and the update content.

Here is the basic syntax for updating a record:

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

Among them, the update condition specifies the content that needs to be updated. Upsert is used to specify whether to insert a new document if there is no matching document, defaulting to false. Multi is used to specify whether to update multiple documents at the same time, defaulting to false.

For example, suppose there is a collection named “users” and you need to update the name of the user with id 1 to “John”. You can use the following command:

db.users.update(
   { id: 1 },
   { $set: { name: "John" } }
)

The above command will update the name of the user with id 1 to “John”.

bannerAds