MongoDB and employees & departments, part 2

There are several possibilities in MongoDB to make our DEPT/EMP model.

The first possibility is to make embedded documents like this:

db.dept.insert(

{“dept”: “DALLAS”,
“emp” :{“ename” :”Eric”,”sal”: “5000”,”comm” : “500”}

},

{“dept”: “DALLAS” ,
“emp”:{“ename” :”Michel”,”sal”: “6000”,”comm” : “100”}

}
)

So EMP is embedded inside DEPT.  I put intentionally this white spaces in order to make the commands more clear. If you do copy and paste in your MongoDB environnement, it will work.

Nothing prevents you to write the code in this way:

db.dept.insert({“dept”: “DALLAS”, “emp” :{“ename” :”Eric”,”sal”: “5000”,”comm” : “500”}},{“dept”: “DALLAS” ,”emp”:{“ename” :”Michel”,”sal”: “6000”,”comm” : “100”} }
)

But it is less clear IMHO.

Ok, and now, we’ll do some updates.

For exemple, in SQL we will do the following to increase the salary of one of the employees.

update emp

set sal=sal+100

where empno=1234

The same thing in MongoDB will be done with the following command:

db.emp.update({“empno”:”1234″},{“$inc”:{“sal”:100}})

The $inc operator is used to add the 100 dollars to the salary of the employee with empno 1234.

Note: In MongoDB the command update will change the value of the first document found, not the entire subset returned.  In our case above there is only one document returned so it does not matter, but if we have chosen some other criteria, for example to increase for 100 dollars all the employees that earn 1000 dollars, this will update just the first document found.

db.emp.update({“sal”:”1000″},{“$inc”:{“sal”:100}})

So an additional clause will be necessary to update more documents

db.emp.update({“sal”:”1000″},{“$inc”:{“sal”:100}},true)

To be continued …

http://www.lyticsware.com

Leave a comment