Dear readers of our blog, we'd like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.
 
SQLS*Plus - best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.
 

REQUEST COMPLIMENTARY SQLS*PLUS LICENCE

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

MongoDB: Update Data

18 September 2020

MongoDB: Data Update

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

 
Tags: , , ,

MORE NEWS

 

Preamble​​NoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...

Preamble​​MongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...

5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...

The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...

Preamble​​MS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...

First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...

Preamble​​Atom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...

Preamble​​MongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...

FlexibilityOne of the most advertised features of MongoDB is its flexibility.  Flexibility, however, is a double-edged sword. More flexibility means more...

Preamble​​SQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...

Preamble​​Writing an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...

Preamble​​Oracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...

Preamble​​IBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...

  What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....

Preamble​​If you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...

Preamble​​Starting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...