12-12 04:59
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[MongoDB] Update Modifiers / Part. 3 - $inc 본문

Data Science/MongoDB

[MongoDB] Update Modifiers / Part. 3 - $inc

cinema4dr12 2014. 1. 20. 23:45

Written by cinema4d

Incrementing & Decrementing

The "$inc" modifier changes the value for an existing key which is type "number" or creates a new key of type "number" if not exist.

Suppose we are managing the scores of students, for example:

// define
var student1 = {"name" : "gchoi", "score" : 90};
var student2 = {"name" : "jmpark", "score" : 40};

// insert
db.student.insert(student1);
db.student.insert(student2);

 

Check the result:

> db.student.find() { "_id" : ObjectId("52dd2a8835f6aa029e32a28a"), "name" : "gchoi", "score" : 90 } { "_id" : ObjectId("52dd2a8935f6aa029e32a28b"), "name" : "jmpark", "score" : 40 }

The student "jmpark" studied very hard to increment his score by 60 points. As a result he earns 100 points.

The modifier "$inc" is used to increase the score of the student "jmpark" as:

db.student.update({"name" : "jmpark"}, {"$inc" : {"score" : 60}});

 

Result:

> db.student.find() { "_id" : ObjectId("52dd2a8835f6aa029e32a28a"), "name" : "gchoi", "score" : 90 } { "_id" : ObjectId("52dd2a8935f6aa029e32a28b"), "name" : "jmpark", "score" : 100 }


Comments