0% found this document useful (0 votes)
10 views2 pages

Update in Mongodb

Uploaded by

nootanpadia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

Update in Mongodb

Uploaded by

nootanpadia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Update document

update() method is used.


-update the value in the existing document

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 :

1. $inc - Increments the value of the field by the specified amount.


2. $mul - Multiplies the value of the field by the specified amount.
3. $rename - Renames the field.
4. $setOnInsert - Sets the value of a field if an update results in an insert of a
document. Has no effect on update operations that modify the existing document.
5. $set - sets the value of field in a document.
6. $unset - Removes the specified field from a document.
7. $min - Only updates the field if the specified value is less than the existing
field value.
8. $max - Only updates the field if the specified value is greater than the
existing field value.

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}
)

You might also like