Page Content

Tutorials

How do you Update Documents in MongoDB?

Update Documents in MongoDB

Within a collection, you can edit documents that already exist in MongoDB. In order to preserve dynamic data, updates are essential. MongoDB lets you replace a full document or edit selected fields using update operators.

Performance and Atomicity MongoDB’s document-level update operations are atomic. Accordingly, a single write action is assured to finish completely or not at all, even if it changes several embedded documents inside a single main document. In just one document, this guarantees data consistency. However, operations that impact several documents may interleave since they are not atomic as a whole.

The way updates work can vary. Because operations like $inc on an integer happen “in-place” on disc, they are very efficient and don’t alter the size of the document. However, MongoDB may need to move the document on disc, which can be more costly, in order to accommodate updates that expand a document’s size (such as adding a new field or pushing to an array). MongoDB makes an effort to counteract this by modifying a padding factor, particularly for the storage engine MMAPv1.

The Method

Modifying existing documents is primarily accomplished with the db.collection.update() method. It requires two or more parameters:

  • SELECTIOIN_CRITERIA (query document): Which documents should be updated is specified by the query document’s SELECTIOIN_CRITERIA. Similar to read operations, it employs the same query syntax.
  • UPDATED_DATA (modifier document or replacement document): The modifier document, also known as the replacement document, UPDATED_DATA, specifies how the chosen documents must be changed.

An options document with parameters like upsert and multi can also be accepted.

Document Replacement

When a document with no update operators (such as $set, $inc, etc.) is sent as the UPDATED_DATA parameter, MongoDB will substitute the new document you supplied for the entire existing document that fits the SELECTIOIN_CRITERIA. We will eliminate any fields that are not specified in the updated text.

Example of Document Replacement: Let’s say you have a mycol collection with a document: { “_id” : ObjectId(5983548781331adf45ec5), “title”:”MongoDB Overview”}.

If you run: > db.mycol.update({ “_id” : ObjectId(“5983548781331adf45ec5”)}, {“title”:”New Title”, “description”: “New Description”}) The original document would be replaced, and any fields not in the replacement document would be lost. You should be careful when using this type of update.

Modifier-Based Updates

In order to change only particular fields in a document, you need to utilise update operators. These operations allow individual fields to be updated atomically.

These update operators are frequently used:

  • $set operator: The value of a particular field can be set using the $set operator. Should the field be absent, $set will generate it. It has the ability to alter the type of key it alters as well.
  • Example of $set: To alter a document’s title from “MongoDB Overview” to “New MongoDB Tutorial,” use the following example of $set: > Mycol.update in dbFrom {‘title’:’MongoDB Overview’} to{$set:{‘title’:’New MongoDB Tutorial’}}
  • You can use the $set object to change several fields at once: > db.student.update({name: ‘Tom’}, {$set: {sex: ‘F’, age: 40}}).
  • Use dot notation to change fields in embedded documents by using $set: > db.inventory.update({ item: “ABC1” }, { $set: { “details.model”: “14Q2” } }
  • $inc operator: Using the $inc operator, a numeric value in a field can be atomically increased or decreased. It will be created and set to the increment amount if the field is not already there. The fact that this operator usually produces in-place disc updates makes it extremely efficient. It will not work with other data types, though, as $inc may only be applied to fields that contain numeric values (integer, long, or double).
  • Example of $inc: To increase the ‘Read’ volume of the ‘One Piece’ manga by 4: > db.media.update ( { “Title”: “One Piece”}, {$inc: {“Read” : 4} }) 520 + 4 would make the ‘Read’ field 524.
  • To subtract 2 from ‘vampires’ for ‘Pilot’: > db.unicorns.update({name: ‘Pilot’}, {$inc: {vampires: -2}})
  • $push operator: An array field can be appended with a value using the $push operator. A new array with the value will be created if the field is not present. The field will cause an error if it exists but is not an array.
  • Example of $push: To add “sugar” to the “loves” array of “Aurora”: > db.unicorns.update\name: ‘Aurora’}, {$push: {loves:’sugar’}}
  • Using $each in combination with $push: > db.products.update allow you to add several values in a single action.With {slug:’shovel’} and {$push: {tags: {$each: [‘tools’, ‘soil’, ‘garden’]}}},
  • Additional relevant array operators consist of:
    • $addToSet: Like $push, but in order to ensure uniqueness, it only adds the value if it isn’t already in the array.
    • $pop: The first or final element in an array can be removed with $pop.
    • $pull: The $pull function eliminates every instance of a given value or values from an array.
    • $pullAll: Extracts from an array several elements with distinct values.
    • Positional Operator ($): Using the positional operator ($), one can update a subdocument or element in an array by matching a criterion inside the array without knowing its precise index. People.update in db{name: “Tom”, “marks.subject”: “English”},{“$set”:{“marks.$.marks”: 85}}

Updating Single vs. Multiple Documents

Only the first document that meets the given SELECTIOIN_CRITERIA will be updated by default when using the db.collection.update() method.

You must set the options document’s multi parameter to true in order to update several documents that meet the requirements.

Example of updating multiple documents: Consider the mycol collection with data52: { “_id” : ObjectId(598354878df45ec5), “title”:”MongoDB Overview”} { “_id” : ObjectId(59835487adf45ec6), “title”:”NoSQL Overview”} { “_id” : ObjectId(59835487adf45ec7), “title”:”Tutorials Point Overview”}

To set the new title ‘New MongoDB Tutorial’ for all documents whose title is ‘MongoDB Overview’, you’d use: > db.mycol.update({‘title’:’MongoDB Overview’}, {$set:{‘title’:’New MongoDB Tutorial’}},{multi:true}).

Update techniques that are more recent (MongoDB 3.2.x and beyond) New update methods were developed by MongoDB to improve clarity and precise intent:

db.collection.updateOne(): Updates only a single document that matches the criteria.

db.collection.updateMany(): Updates all documents that match the criteria.

db.collection.replaceOne(): Replaces a single document that matches the criteria.

By expressing nMatched (number of documents matched) and nModified (number of documents actually altered), these more recent methods frequently provide a WriteResult object at completion.

MongoDB document updating provides a strong and adaptable approach to data management, enabling accurate edits or more extensive schema changes based on your requirements.

Index