Database Reference
In-Depth Information
$set can even change the type of the field it modifies. For instance, if we decide that we
would like to store the character string three instead of 3 , we can run this statement:
db.book.update ( { titleName : “Fifty Shades of Data Modeling” },
{ “$set” : { edition : “three” } } )
If we decide the edition field really isn't needed anyway, we can remove this field alto-
gether with $unset:
db.book.update ( { titleName : “Fifty Shades of Data Modeling” }, { “$unset” : { edition : “three” } } )
The $inc modifier can be used to increment the value of an existing field and, similar to
$set, can be used to create a new field if it does not already exist. For example, let's say we
would like to add a field called bookTotalCopiesSoldCount , which specifies how many
copies of a title have been sold since the topic was first published. We can run this state-
ment:
db.book.update ( { titleName : “Fifty Shades of Data Modeling” },
{ “$inc” : { bookTotalCopiesSoldCount : 3000 } } )
If we look at the document after this update, we'll see the following:
db.book.find ( { titleName : “Fifty Shades of Data Modeling” } )
{ “_id” : ObjectId(“530f8be4d77a08823086017d”), “titleName” : “Fifty Shades of Data Modeling”, “bookTotalCop-
iesSoldCount” : 3000 }
Next month, after 100 more copies of this title are sold, we can run this statement to add
100 more copies to the total:
db.book.update ( { titleName : “Fifty Shades of Data Modeling” },
{ “$inc” : { bookTotalCopiesSoldCount : 100 } } )
If we look at the document after this update, we'll see the following:
db.book.find( { titleName : “Fifty Shades of Data Modeling” } )
{ “_id” : ObjectId(“530f8be4d77a08823086017d”), “titleName” : “Fifty Shades of Data Modeling”, “bookTotalCop-
iesSoldCount” : 3100 }
There are many more ways to update data and especially ways to update data in arrays.
Please refer to the MongoDB user guide for more information.
Search WWH ::




Custom Search