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?

1.2 Why MongoDB?

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

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:

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

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

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

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:

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

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

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:

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

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:

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:

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

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

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:

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

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.

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:

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
Exit mobile version