Update in Mongodb
Update in Mongodb
syntax :
db.collection_name.update(
{selection_criteria},
{updated_data},
{options}
)
here,
-selection_criteria = query
- updated_data : {update_operator : {key : value}}
-options : optional
1. multi - boolean - true then it will update multiple documents.
2. upsert - boolean - true then update + insert
update operators :
E.g :
1. Increment salary by 2000 where the emp name is sachin.
db.emp.update(
{ename:"sachin"},
{$inc : {sal : 2000}}
)
2. Increment salary by 2000 of all the employees.
db.emp.update(
{},
{$inc : {sal : 2000}},
{multi:true}
)
3. Update designation of sachin with CEO.
db.emp.update(
{ename:"sachin"},
{$set:{desig:"CEO"}}
)
4. Add a new field "remark" to document with name dhoni and set remark head.
db.emp.update(
{ename:"dhoni"},
{$set : {remark : "head"}}
)
5. Remove the added new field.
db.emp.update(
{ename:"dhoni"},
{$unset : {remark : "head"}}
)
6. Update designation fo sachin with MD and insert as new document.
db.emp.update({ename:"sachin"},
{$set : {desig : "MD"}},
{upsert : true}
)
Note : if the document is matched with the query then only updation will be done.
if the document is not matched with the query, then the new document will be
inserted.
db.emp.update({_id : 9,ename:"sachin",sal:65000,dept:"sales"},
{$setOnInsert : {desig : "MD"}},
{upsert : true}
)