Preamble
Like other database management systems, MongoDB provides an opportunity to update data. The easiest to use method is to save. This method accepts a document as a parameter.
Method of saving
The _id parameter may be passed into this document as a field. If the method finds a document with such value _id, the document shall be updated. If there are no documents with such a _id, the document is inserted.
If the _id parameter is not specified, the document is inserted, and the _id parameter is generated automatically as if it was normally added through the insert function:
db.users.save({name: "Eugene", age : 29, languages: ["english", "german", "spanish"]})
As a result, the function returns a WriteResult object. For example, if we save it successfully, we get it:
WriteResult({"nInserted" : 1 })
MongoDB update
The update function offers a more detailed setup during an update. It accepts three parameters:
- query: it accepts a request to select the document to be updated.
- objNew: presents a document with new information that will replace the old one when it is updated.
- options: defines additional settings when updating documents. It can accept two arguments: upsert and multi.
If the upsert parameter is true, mongodb will update the document if it is found, and create a new one if it is not. If it is false, mongodb will not create a new document if the sample request does not find a single document.
The multi-option specifies whether the first element in the sample should be updated (used by default if this option is not specified) or whether all documents in the sample should be updated.
For example:
db.users.update({name : "Tom"}, {name: "Tom", age : 25}, {upsert: true})
The document found by the query {name : “Tom”} will now be overwritten by the document {“name”: “Tom”, “age” : “25”}.
The update() function also returns the WriteResult object. For example:
WriteResult({"nMatched" : 1, "nUpserted": 0, "nModified": 1})
In this case, the result tells us that there is one document that satisfies the condition and one document was updated.
Updating a separate field
Often, you do not need to update the entire document, but only the value of one of its keys. The $set operator is used for this purpose. If the document does not contain an updatable field, it is created.
db.users.update({name : "Tom", age: 29}, {$set: {age : 30}})
If there is no field to be updated in the document, it is added to it:
db.users.update({name : "Tom", age: 29}, {$set: {salary : 300}})
In this case, only one document was updated, the first in the sample. By specifying multi: true, we can update all documents in the sample:
db.users.update({name : "Tom"}, {$set: {name : "Tom", age : 25}}, {multi:true})
To simply increase the value of the numeric field by a certain number of units, the $inc operator is used. If a document does not contain an updatable field, it is created. This operator is applicable only to numerical values.
db.users.update({name : “Tom”}, {$inc: {age:2}})
Field Removal
To delete a separate key, the $unset operator is used:
db.users.update({name : "Tom"}, {$unset: {salary: 1}})
If suddenly such a key does not exist in the document, the operator has no influence. You may also delete several fields at once:
db.users.update({name : “Tom”}, {$unset: {salary: 1, age: 1}})
updateOne and updateMany
The updateOne method is similar to the update method except that it updates only one document.
db.users.updateOne({name : "Tom", age: 29}, {$set: {salary : 360}})
If you need to update all documents that meet some criteria, the updateMany() method is applied:
db.users.updateMany({name : "Tom"}, {$set: {salary : 560}})
Array update Operator $push
The $push operator allows you to add another value to an already existing one. For example, if the key stores an array as a value:
db.users.updateOne({name : "Tom"}, {$push: {languages: "russian"}})
If the key for which we want to add the value does not represent an array, we get a Cannot apply $push/$pushAll modifier to non-array error.
Using the $each operator, we can add several values at once:
db.users.update({name : "Tom"}, {$push: {languages: {$each: ["russian", "spanish", "italian"]}})
A couple more operators allow you to customize the insert. The $position operator specifies the position in the array for inserting elements, and the $slice operator specifies how many elements should be left in the array after insertion.
db.users.update({name : "Tom"}, {$push: {languages: {$each: ["german", "spanish", "italian"], $position:1, $slice:5}}})
In this case, the elements [“german”, “spanish”, “italian”] will be inserted into the languages array from the 1st index, and after inserting, only the first 5 elements will remain in the array.
Array update Operator $addToSet
The $addToSet operator adds objects to the array like the $push operator. The difference is that $addToSet adds data if it is not already in the array:
db.users.update({name : "Tom"}, {$addToSet: {languages: "russian"}})
Removal of an element from an array
The $pop operator allows to remove an element from an array:
db.users.update({name : "Tom"}, {$pop: {languages: 1}})
By specifying 1 for the key, we remove the first element from the end. To remove the first element from the array first, we must pass a negative value:
db.users.update({name : "Tom"}, {$pop: {languages: -1}})
The $pull operator implies a slightly different action. It removes every occurrence of an item in the array. For example, with the $push operator we can add the same value several times to an array. And now with the $pull operator, we remove it:
db.users.update({name : "Tom"}, {$pull: {languages: "english"}})
And if we want to remove more than one value, then we can use the $pullAll operator:
db.users.update({name : "Tom"}, {$pullAll: {languages: ["english", "german", "french"]}})
MongoDB Tutorial for Beginners – MongoDB Update Document
Enteros
About Enteros
IT organizations routinely spend days and weeks troubleshooting production database performance issues across multitudes of critical business systems. Fast and reliable resolution of database performance problems by Enteros enables businesses to generate and save millions of direct revenue, minimize waste of employees’ productivity, reduce the number of licenses, servers, and cloud resources and maximize the productivity of the application, database, and IT operations teams.
The views expressed on this blog are those of the author and do not necessarily reflect the opinions of Enteros Inc. This blog may contain links to the content of third-party sites. By providing such links, Enteros Inc. does not adopt, guarantee, approve, or endorse the information, views, or products available on such sites.
Are you interested in writing for Enteros’ Blog? Please send us a pitch!
RELATED POSTS
Revolutionizing Cost Allocation and Attribution in Real Estate with Enteros: Optimizing Database Performance for Better Financial Insights
- 24 December 2024
- Database Performance Management
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…
Enteros: Streamlining Root Cause Analysis and Shared Cost Optimization with Cloud FinOps in the Public Sector
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…
Optimizing Database Performance with Enteros: Leveraging Cloud FinOps and Observability for the Financial Sector
- 23 December 2024
- Database Performance Management
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…
Enteros: Enhancing Database Security Cost Management with RevOps and AIOps for the Insurance Sector
In the fast-evolving world of finance, where banking and insurance sectors rely on massive data streams for real-time decisions, efficient anomaly man…