MongoDB Update Documents – MongoDB CRUD Operations Part 2

In this chapter, we will talk about MongoDB update documents – how to update documents in the collection. There are many ways from which we can update documents in the collection:

  1. collection.updateOne()
  2. collection.updateMany()
  3. collection.update()
  4. collection.findOneAndUpdate()
  5. collection.replaceOne()
  6. collection.findOneAndReplace()
  7. collection.findAndModify()
  8. collection.save()

Let’s read about them in brief.


MongoDB Update Documents


There are many update methods to update documents in MongoDB as mentioned above. Let’s go through these methods to understand it better.

1) collection.updateOne()

This update statement updates the FIRST document that matches the given filter. The filter is any criteria based on which we want to update document (such as age=18, color=red etc.)

Following is a sample MongoDB update command

db.students.updateOne(

   { "age": 18 },

   {

     $set: { "canVote": "True" }, // Here you can update as many parameters as you want

   }

)

This update commands use the age =18 as a filter (match the query) in the collection “students”. $set operator (called as update operators) updates the value of the canVote to True.

You can update multiple parameters, they need to be separated by a comma (,).E.g.:

$set: { "canVote": "True", “isAdult”=”Yes” },
  • collection.updateMany()

This command is similar to db.collection.updateOne() but the only difference is that it updates ALL the documents that match the filter in the collection. (i.e to update multiple documents)

db.students.updateMany(

   { "age": 18 },

   {

     $set: { "canVote": "True" },

   }

)

Here, ALL the documents having age=18 get updated to canVote to “True”.

  • collection.update()

This command works as both updateOne and updateMany command.

As UpdateOne() command:

db.students.update (

   { "age": 18 },

   {

     $set: { "canVote": "True" },

   }

)

Here, it will update only first document that matches the filter.

As UpdateMany() Command:

db.students.update (

   { "age": 18 },

   {

     $set: { "canVote": "True" },

   },

{ multi: true } // Additional Parameter

)

Here, by using one additional parameter – multi: true it works as updateMany() and updates all documents that match the filter.

  • collection.findOneAndUpdate()

This updates a single document based on the filter and other criteria.

The simple syntax is db.collection.findOneAndUpdate(filterupdateoptions)

The findOneAndUpdate() method has the following form:

db.collection.findOneAndUpdate(

   <filter>,

   <update>,

   {

     projection: <document>,

     sort: <document>,

     returnNewDocument: <boolean>

   }

)

Here, we have some additional parameters which are as follows:

  • Projection: Optional. It denotes A subset of fields to return. If you want to return all fields in the returned document, do not include this parameter.
  • Sort: Specifies a sorting order for the documents matched by the filter.
  • returnNewDocument: It returns the updated document instead of the original document when set to true.
  • collection.replaceOne()

This command replaces at most a single document (replace an existing document) that matches a specified filter even though multiple documents may match the specified filter.

The replaceOne() method has the following form:

db.collection.replaceOne(

   <filter>,

   <replacement>,

   {

     upsert: <boolean>,

     writeConcern: <document>

   }

)

Here, upsert is of boolean type. It can be described as upsert true or upsert false. If set to true, it creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.

  • collection.findOneAndReplace()

This command modifies and replaces a single document based on the filter and sort criteria.

The findOneAndReplace() method has the following form:

db.collection.findOneAndReplace(

   <filter>,

   <replacement>,

   {

     projection: <document>,

     sort: <document>,

     maxTimeMS: <number>,

     upsert: <boolean>,

     returnNewDocument: <boolean>

   }

)
  • collection.findAndModify()

This command modifies and returns a single document. But the key point to be noted here is that by default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

The findAndModify() method has the following form:

db.collection.findAndModify({

    query: <document>,

    sort: <document>,

    remove: <boolean>,

    update: <document>,

    new: <boolean>,

    fields: <document>,

    upsert: <boolean>,

    bypassDocumentValidation: <boolean>,

    writeConcern: <document>

});

  • collection.save()

This command updates an existing document or inserts a new document (If the document is not present), depending on its document parameter.

The save() method has the following form:

db.collection.save(

   <document>,

   {

     writeConcern: <document>

   }

)

mongodb update documents

That’s it in this MongoDB update documents – MongoDB CRUD Operations Part 2. In the next chapter, we will read about MongoDB delete documents (CRUD Operations Part 3). If you have any queries, please comment in the comment section below. Also, do share your feedback 🙂

Mohit Arora
Follow me