Database Reference
In-Depth Information
So, if we would like to update the title for Data Modeling for MongoDB , we can execute
this statement:
db.book.update( { titleName : “Data Modeling for MongoDB” },
{ titleName : “Fifty Shades of Data Modeling” } )
Because we left off the multi and upsert parameters, we would only change the first occur-
rence of this title, and if this title did not exist in our collection, we would not insert this
title as a new document.
If we wanted to update all documents that meet this criteria, we can execute this statement:
db.book.update( { titleName : “Data Modeling for MongoDB” },
{ titleName : “Fifty Shades of Data Modeling” }, { multi: true } )
Note that the basic update function is designed for addressing the situation when what you
are searching for and what you are changing are the same fields. If we wanted to change a
different field than the one being searched for, you will need to use the $set command:
db.book.update ( {_id : ObjectId(“530f8be4d77a08823086017d”) },
{ “$set” : { titleName : “Fifty Shades of Data Modeling” } } )
What would happen if we wanted to update a field but the field did not exist? The solution
is to again use $set. $set sets the value of a field. If the field does not yet exist, it will be
created. If the field does exist, it will be updated with the value specified by $set. This can
be handy for updating schema or adding user-defined fields. For example, if we wanted to
update the edition but edition did not exist, we can run this statement:
db.book.update ( { titleName : “Fifty Shades of Data Modeling” },
{ “$set” : { edition : 2 } } )
Now this document will have an edition field:
db.book.find( { titleName : “Fifty Shades of Data Modeling” } )
{ “_id” : ObjectId(“530f8be4d77a08823086017d”), “titleName” : “Fifty Shades of Data Modeling”, “edition” : 2 }
If we decided that this topic is really the third edition and not the second edition, $set can
be used again to change the value:
db.book.update( { titleName : “Fifty Shades of Data Modeling” },
{ “$set” : { edition : 3 } } )
Search WWH ::




Custom Search