Update Operator $inc: Increment Field Values In MongoDB

MongoDB provides a flexible document-based data model that allows developers to easily store semi-structured and unstructured data. One of the fundamental concepts in MongoDB is the use of operators, which are used to perform specific operations on values.

The MongoDB field update operator is an operator that enables developers to update specific fields within a document.

In this tutorial, we’ll focus primarily on the $inc operator to increment and decrement field values and provide you with several examples of how to use it for your next project.

Also Read: Update Operator in MongoDB

Introduction to $inc Operator 

The $inc operator is used to increment the value of a given field by a specified amount. This operator accepts both positive and negative values for addition. Moreover, if a given field does not exist, then the $inc operator creates the field and attaches the specified value to it. When a null value is provided, the operator throws an error.

If the user passes an empty operand expression like so: { }, then this operator will no longer throw an error (starting from MongoDB 5.0). The update operation is thus no-op.

Syntax:

Let us take a quick look at the $inc operator syntax.

{ $inc: { field1: amount1, field2: amount2, ... } }

Examples of Using the $inc Operator in MongoDB

We have inserted several documents into a collection ‘cats’ of the database ‘petShop’ to demonstrate several examples.

Following are the documents inside the ‘cats’ collection in the ‘petShop’ database:

> db.cats.find().pretty()
{
        "_id" : ObjectId("602eb6c728ff814b64eb3411"),
        "name" : "Stephanie",
        "age" : 18,
        "breed" : "Persian",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : true
        }
}
{
        "_id" : ObjectId("602eb73728ff814b64eb3412"),
        "name" : "Whiskers",
        "age" : 3,
        "breed" : "Scottish Fold",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : true
        }
}
{
        "_id" : ObjectId("602eb84628ff814b64eb3413"),
        "name" : "Krissy",
        "age" : 5,
        "breed" : "Turkish Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebc5ea78db75e09057cd0"),
        "name" : "Cassy",
        "age" : 15,
        "breed" : "Japanese Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebc9da78db75e09057cd1"),
        "name" : "Shane",
        "age" : 10,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebed7a78db75e09057cd2"),
        "name" : "Phoebe",
        "age" : 20,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        }
}

We have 6 documents in the collection.

Increment the value of the field using the $inc operator

Let’s now demonstrate an example of using the $inc operator in MongoDB using a positive value to increment the value of a field by a specified value. 

Let’s suppose we forget to update the age of the cats on our website for three years. In this case, we can simply use the $ince operator and define the field as ‘age’ and the amount as ‘3’ to increase the value of the ‘age’ filed by 3 for each document matching a certain condition which we are not going to pass for this example as we want to update every single document. This is also the reason we are using the updateMany() method instead of the updateOne() method.

Below is the query to increment the ‘age’ field by 3:

> db.cats.updateMany(
...    { },
...    { $inc: { age: 3 } }
... )
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
> db.cats.find().pretty()
{
        "_id" : ObjectId("602eb6c728ff814b64eb3411"),
        "name" : "Stephanie",
        "age" : 21,
        "breed" : "Persian",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : true
        }
}
{
        "_id" : ObjectId("602eb73728ff814b64eb3412"),
        "name" : "Whiskers",
        "age" : 6,
        "breed" : "Scottish Fold",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : true
        }
}
{
        "_id" : ObjectId("602eb84628ff814b64eb3413"),
        "name" : "Krissy",
        "age" : 8,
        "breed" : "Turkish Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebc5ea78db75e09057cd0"),
        "name" : "Cassy",
        "age" : 18,
        "breed" : "Japanese Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebc9da78db75e09057cd1"),
        "name" : "Shane",
        "age" : 13,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebed7a78db75e09057cd2"),
        "name" : "Phoebe",
        "age" : 23,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        }
}

The document got as a result has the field ‘age’ increased by the specified amount.

Decrement the value of the field using the $inc operator

We can increment a field value by a negative number to decrease the value. In simple words, the addition of a negative number to another number will subtract the numbers instead of adding them.

In the above example, we have increased ‘age’ to 3, let’s say we are wrong and now we want to decrease it by 2.

Below is the statement to decrement the ‘age’ field by 3:

> db.cats.updateMany(
...    { },
...    { $inc: { age: -2 } }
... )
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
> db.cats.find().pretty()
{
        "_id" : ObjectId("602eb6c728ff814b64eb3411"),
        "name" : "Stephanie",
        "age" : 19,
        "breed" : "Persian",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : true
        }
}
{
        "_id" : ObjectId("602eb73728ff814b64eb3412"),
        "name" : "Whiskers",
        "age" : 4,
        "breed" : "Scottish Fold",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : true
        }
}
{
        "_id" : ObjectId("602eb84628ff814b64eb3413"),
        "name" : "Krissy",
        "age" : 6,
        "breed" : "Turkish Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebc5ea78db75e09057cd0"),
        "name" : "Cassy",
        "age" : 16,
        "breed" : "Japanese Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebc9da78db75e09057cd1"),
        "name" : "Shane",
        "age" : 11,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        }
}
{
        "_id" : ObjectId("602ebed7a78db75e09057cd2"),
        "name" : "Phoebe",
        "age" : 21,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        }
}

Perfect! The values are now decremented.

Passing a Missing Nested Field to the inc operator in MongoDB

In this example, we will use the $inc operator with a field that is not only missing but also nested to see what happens.

Let’s say we want to add a cost field that is nested inside the ‘moreDetails’ field and set a value for each of them. We have no such field in existing data, so let’s verify whether this operator is able to create it or not.

Below is the statement to create a ‘cost’ field inside the missing field ‘moreDetails’:

> db.cats.updateMany(
...    { },
...    { $inc: { "moreDetails.cost": 20000 } }
... )
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
> db.cats.find().pretty()
{
        "_id" : ObjectId("602eb6c728ff814b64eb3411"),
        "name" : "Stephanie",
        "age" : 19,
        "breed" : "Persian",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : true
        },
        "moreDetails" : {
                "cost" : 20000
        }
}
{
        "_id" : ObjectId("602eb73728ff814b64eb3412"),
        "name" : "Whiskers",
        "age" : 4,
        "breed" : "Scottish Fold",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : true
        },
        "moreDetails" : {
                "cost" : 20000
        }
}
{
        "_id" : ObjectId("602eb84628ff814b64eb3413"),
        "name" : "Krissy",
        "age" : 6,
        "breed" : "Turkish Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        },
        "moreDetails" : {
                "cost" : 20000
        }
}
{
        "_id" : ObjectId("602ebc5ea78db75e09057cd0"),
        "name" : "Cassy",
        "age" : 16,
        "breed" : "Japanese Angora",
        "personality" : {
                "dogFriendly" : true,
                "childFriendly" : false
        },
        "moreDetails" : {
                "cost" : 20000
        }
}
{
        "_id" : ObjectId("602ebc9da78db75e09057cd1"),
        "name" : "Shane",
        "age" : 11,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        },
        "moreDetails" : {
                "cost" : 20000
        }
}
{
        "_id" : ObjectId("602ebed7a78db75e09057cd2"),
        "name" : "Phoebe",
        "age" : 21,
        "breed" : "Bobtail",
        "personality" : {
                "dogFriendly" : false,
                "childFriendly" : false
        },
        "moreDetails" : {
                "cost" : 20000
        }
}

Perfect! We now have a ‘moreDetails’ field with a nested ‘cost’ field in each of the documents and they have a value of 20000.

Read More: Listing All Collections, Databases, and Users in the MongoDB Shell [Easy Guide]

Conclusion

In this tutorial, we learned to use the $inc operator in MongoDB with multiple examples. We have seen that this operator not only helps in increasing the value of the field but also helps in reducing the values ​​using negative numbers. Hope you enjoyed reading this tutorial.

Reference

https://www.mongodb.com/docs/manual/reference/operator/update/inc/

Aneesha S
Aneesha S
Articles: 172