Increment($inc) operator: MongoDB


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

inc operator with update

test database, names collection

1
2
3
4
5
6
7
8
9
10
11
12
> 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> 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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> 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 https://www.youtube.com/watch?v=LjJJOY4DLMs]

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



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> 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).

Leave a Reply

Your email address will not be published. Required fields are marked *