Increment($inc) operator: MongoDB

Lets learn how to use $inc operator with update() method in MongoDB.

test database, names collection

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Here we have 2 documents. And we’ll be working on first document to illustrate the working of $inc operator.

> db.names.update({"Company": "Google"}, {$inc: {"No": 2}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 3
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Here “No” field will be incremented by 2. So the final value of “No” field is 3 (1+2).

> db.names.update({"Company": "Google"}, {$inc: {"Sl_no": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 3,
        "Sl_no" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

If we apply $inc operator on an non-existing field, it will be created with the increment value itself.

Increment($inc) operator: MongoDB



YouTube Link: https://www.youtube.com/watch?v=LjJJOY4DLMs [Watch the Video In Full Screen.]



> db.names.update({"Company": "Google"}, {$inc: {"No": 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.names.find().pretty()
{
        "_id" : ObjectId("53c3fc2005e0ce2719d91bd2"),
        "Company" : "Google",
        "No" : 4,
        "Sl_no" : 1
}
{
        "_id" : ObjectId("53c3fd3bb9ae26fa217b1e12"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 2
}

Here we increment the value of “No” once again by 1. So the final value of “No” field is 4 (3+1).