MongoDB

MongoDB Field Update Operators Tutorial

Hello readers, in this tutorial, we will understand the different Field Update Operators available in the Mongo database. Let’s study in brief the different ways in which these operators can be used.

1. Introduction

If you have installed the MongoDB application (version 3.6.X) on Windows or Ubuntu operating system and you wish to learn the field update operators, then follow the below steps. It is very simple, but before moving further let’s take a look at MongoDB and its features.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.2 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

2. MongoDB Field Update Operators Tutorial

In this tutorial, we will learn how to handle the different field update operators provided by the Mongo database. But before moving further with the tutorial, we will need to create the sample collection. The following script creates a database called office with a collection as emp. Open the Mongo terminal and execute the script.

> use office

> db.emp.insertMany( [
	{ "_id" : "101", "name" : "Daniel Atlas", "age": 26, "unit_tag_code": "tech_1001" }, 
	{ "_id" : "102", "name" : "Charlotte Neil", "age": 30, "unit_tag_code": "hr_1002" },
	{ "_id" : "103", "name" : "James Breen", "age": 32, "unit_tag_code": "payroll_1064" },
	{ "_id" : "104", "name" : "John Gordon", "age": 24, "unit_tag_code": "tech_1001" },
	{ "_id" : "105", "name" : "Rick Ford", "age": 21, "unit_tag_code": "hr_1002" },
	{ "_id" : "106", "name" : "Susan Dixit", "age": 34, "unit_tag_code": "payroll_1064" },
	{ "_id" : "107", "name" : "John Snow", "age": 31, "unit_tag_code": "tech_1001" },
	{ "_id" : "108", "name" : "Arya Stark", "age": 30, "unit_tag_code": "hr_1002" },
	{ "_id" : "109", "name" : "Smith William", "age": 27, "unit_tag_code": "payroll_1064" },
	{ "_id" : "110", "name" : "John Daniel", "age": 29, "unit_tag_code": "tech_1001" }
] )

> db.emp.find()

If everything goes well, the database and the collection will be shown in the Mongo Workbench.

Fig. 1: Database & Collection Creation
Fig. 1: Database & Collection Creation

2.1 $inc Operator

In the Mongo universe, the $inc operator allows the developers to increment or decrement the value of a field by a given amount. In case, the field does not exist in the document, this operator will create a new field and set the field value to the given value. Make note, the use of $inc operator on a field with a null value will throw an error. Here is what the query syntax will look like:

Syntax

> db.collection_name.update( { <query_string> }, {  $inc: { <field1_name>: <amount>, <field2_name>: <amount>, . . . . } } )

Where:

  • The query_string in the update() method is a required input argument that retrieves the documents from a collection on the basis of the given condition
  • The field1_name, field2_name etc. are the field names
  • The amount specifies the increment or the decrement value

Let’s understand this with the help of an example.

2.1.1 $inc operator Example

Consider a scenario where developers want to fetch the documents from a collection having the employee unit tagging as hr_1002 and increment the employee’s age by 2. The following Mongo query can be used:

Query 1

> db.emp.update( { "unit_tag_code": "hr_1002" }, { $inc: { "age": 2 } } );

The query will only increment the age value for the first matching document of the given condition. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 2: Mongo database '$inc' operation
Fig. 2: Mongo database ‘$inc’ operation

2.1.2 $inc operator with ‘multi:true’

Let’s say developers want to add a new field like work_experience with a given value 5 for all the documents that match the given condition. The following Mongo query can be used:

Query 1(a)

> db.emp.update( { "unit_tag_code": "payroll_1064" }, { $inc: { "work_experience": 5 } }, { "multi": true } )

The query with the multi: true option will add the new field (i.e. work_experience) to all the matching documents. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 3: Mongo database '$inc' operation with 'multi: true' option
Fig. 3: Mongo database ‘$inc’ operation with ‘multi: true’ option

2.1.3 $inc operator on Multiple fields

Consider a scenario where developers want to increment the age and work experience for all the matching documents against a given condition. The following Mongo query can be used:

Query 1(b)

> db.emp.update( { "unit_tag_code": "payroll_1064" }, { $inc: { "work_experience": 2, "age": -1 } }, { "multi": true } )

The query with the multi: true option will increment the work experience by 2 and decrement the employee age by 1 for all the matching documents. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 4: Mongo database '$inc' operation on multiple fields
Fig. 4: Mongo database ‘$inc’ operation on multiple fields

2.2 $rename Operator

In the Mongo universe, the $rename operator updates the name of a field. If the field does not exist in the document, this operation will do nothing. Here is what the query syntax will look like:

Syntax

> db.collection_name.update( { <query_string> }, {  $rename: { <old_name1>: <new_name1>, <old_name2>: <new_name2>, . . . . } } )

Where:

  • The query_string in the update() method is a required input argument that retrieves the documents from a collection on the basis of the given condition
  • The old_name1, old_name2 etc. specifies the old name of the fields
  • The new_name1, new_name2 etc. specifies the new name of the fields

Let’s understand this with the help of an example.

2.2.1 $rename operator Example

Let’s say developers want to change the field name to emp_full_name for the documents that match the given condition. The following Mongo query can be used:

Query 2

> db.emp.update( { "unit_tag_code": "tech_1001" }, { $rename: { "name": "emp_full_name", "age": "emp_age" } } )

The query will only rename the field value for the first matching document of the given condition. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 5: Mongo database '$rename' operation
Fig. 5: Mongo database ‘$rename’ operation

2.2.2 $rename operator with ‘multi:true’

If developers want to rename the field values for all the matching documents, they can use the multi: true option in conjugation with the Query 2. The following Mongo query can be used:

Query 2(a)

> db.emp.update( { "unit_tag_code": "tech_1001" }, { $rename: { "name": "emp_full_name", "age": "emp_age" } }, { "multi": true } )

The query will rename the field values for all the matching documents. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 6: Mongo database '$rename' operation with 'multi: true' option
Fig. 6: Mongo database ‘$rename’ operation with ‘multi: true’ option

2.3 $set Operator

In the Mongo universe, the $set operator replaces the field value to a given value. If the field does not exist in the document, this operation will add the new field with the specified value. Here is what the query syntax will look like:

Syntax

> db.collection_name.update( { <query_string> }, {  $set: { <field1>: <value1>, <field2>: <value2>, . . . . } } )

Where:

  • The query_string in the update() method is a required input argument that retrieves the documents from a collection on the on the basis of the given condition
  • The field1, field2 etc. specifies the field whose value is changing
  • The value1, value2 etc. specifies the new value of the field

Let’s understand this with the help of an example.

2.3.1 $set operator Example

Let’s say developers want to change the content of the unit tagging field for the documents that match the given condition. The following Mongo query can be used:

Query 3

> db.emp.update( { "unit_tag_code": "payroll_1064" }, { $set: { "email": "admin@dineresort@com"} }, { "multi": true } )

The query with the multi: true option will update the content of the email field for all the matching documents. Here, if the field does not exist in any document, the $set operator will add this field with the specified value. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 7: Mongo database '$set' operation
Fig. 7: Mongo database ‘$set’ operation

2.4 $setOnInsert Operator

In the Mongo universe, the $setOnInsert operator set values to a field during an upsert only. This operator performs an insert and makes a difference to the update() method on the basis of an upsert flag. Make note:

  • If the update operation has the upsert: true option, it results in the insertion of a document
  • If the update operation does not result in an insert, the $setOnInsert operator does nothing

Here is what the query syntax will look like:

Syntax

> db.collection_name.update( { <query_string> }, {  $setOnInsert: { <field1>: <value1>, <field2>: <value2>, . . . . } }, { "upsert": boolean_value } )

Where:

  • The query_string in the update() method is a required input argument that retrieves the documents from a collection on the on the basis of the given condition
  • The field1, field2 etc. are the field names
  • The value1, value2 etc. are the values to be set for a field

Let’s understand this with the help of an example.

2.4.1 $setOnInsert operator Example to Insert a document

Let’s say developers want to perform an insert using this operator. The following Mongo query can be used:

Query 4

> db.emp.update( { "unit_tag_code": "band_101" }, { $setOnInsert: { "work_description": "Performs required activities", "band_rating": "default" } }, { "upsert": true })

The query will insert a new document in the emp collection and apply a $setOnInsert to the work description and rating fields. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 8: Mongo database '$setOnInsert' operation to Insert a document
Fig. 8: Mongo database ‘$setOnInsert’ operation to Insert a document

2.4.2 $setOnInsert operator Example to Update a document

Let’s say developers want to perform an update using this operator. The following Mongo query can be used:

Query 5

> db.emp.update( { "unit_tag_code": "band_101" }, { $setOnInsert: { "work_description": "Performs required activities", "band_rating": "default" } , $set: { "workforce_strength": 101 } }, { "upsert": true })

As the document already has the work description and rating fields, the query will update the existing document. The database will ignore the $setOnInsert operation and only execute the $set operation.

Fig. 9: Mongo database '$setOnInsert' operation to Update a document
Fig. 9: Mongo database ‘$setOnInsert’ operation to Update a document

2.5 $unset Operator

In the Mongo universe, the $unset operator deletes the given field from the document. This operator has no effect if the given field is not present in the document and has the following prototype form:

Syntax

> db.collection_name.update( { <query_string> }, {  $unset: { <field1>: < ""> } } )

Where:

  • The query_string in the update() method is a required input argument that retrieves the documents from a collection on the on the basis of the given condition
  • The field1 is the name of the field

Let’s understand this with the help of an example.

2.5.1 $unset operator Example

Let’s say developers want to delete the given field from all the matching documents. The following Mongo query can be used:

Query 6

> db.emp.update( { "unit_tag_code": "payroll_1064" }, { $unset: { "email": "" } }, { "multi": true } )

The query with the multi: true option will delete the given field from all the matching documents. To see the updated output, developers can use the find() method as shown in the below image.

Fig. 10: Mongo database '$unset' operation
Fig. 10: Mongo database ‘$unset’ operation

2.6 Other Operators

In the recent release of Mongo documentation, the product owners have added a few more syntaxes specifically to this operation. Let’s review them one by one.

  • $currentDate: This operator sets the value of a field to current date (i.e. either as Date or a Timestamp). For details on this operator, please refer this link
  • $min: This operator updates the field if the given value is less than the existing field value. For details on this operator, please refer this link
  • $max: This operator updates the field if the given value is more than the existing field value. For details on this operator, please refer this link
  • $mul: This operator multiples the value of a field by the given amount. For details on this operator, please refer this link

That’s all for this post. Happy Learning!!

3. Conclusion

In this tutorial, we learned about the different field update operators of the Mongo database. Do remember:

  • The field update operator will only update the first matching document irrespective of the condition that there is more than one matching document
  • Developers can update multiple matching documents by using the { "multi": true } option
  • The find() method used in above expressions displays the documents in a non-structured pattern. If developers want to display the output in a structured pattern, they can use the pretty() method

I hope this article served developers with whatever they were looking for. Developers can download the sample commands in the Downloads section.

4. Download the Eclipse Project

This was an example of the different field update operators available in the Mongo database.

Download
You can download the full source code of this example here: Field_Update_Operators_Cmds

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button