Database Reference
In-Depth Information
"DeskNumber" : 131131,
"Owner" : "Martin, Lisa"
}
} )
// Now, perform the update
>>> collection.update({"ItemNumber" : "6789SID"}, update)
// Inspect the result of the update
>>> collection.find_one({"Type" : "Chair"})
{
u'Status': u'In use',
u'Tags': [u'Chair', u'In use', u'Marketing'],
u'ItemNumber': u'6789SID',
u'Location': {
u'Department': u'Marketing',
u'Building': u'2B',
u'DeskNumber': 131131,
u'Owner': u'Martin, Lisa'
},
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Type': u'Chair'
}
One big minus about this example is that it's somewhat lengthy, and it updates only a few fields. Next, we'll look
at what the modifier operators can be used to accomplish.
Modifier Operators
Chapter 4 detailed how the MongoDB shell includes a large set of modifier operators that you can use to manipulate
your data more easily, but without needing to rewrite an entire document to change a single field's value (as you had
to do in the preceding example).
The modifier operators let you do everything from changing one existing value in a document, to inserting an
entire array, to removing all entries from multiple items specified in an array. As a group, these operators make it easy
to modify data. Now let's take a look at what the operators do and how you use them.
Increasing an Integer Value with $inc
You use the $inc operator to increase an integer value in a document by the given number, n. The following example
shows how to increase the integer value of Location.Desknumber by 20:
>>> collection.update({"ItemNumber" : "6789SID"}, {"$inc" : {"Location.DeskNumber" : 20}})
Next, check to see whether the update worked as expected:
>>> collection.find_one({"Type" : "Chair"}, fields={"Location" : "True"})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Location': {
u'Department': u'Marketing',
u'Building': u'2B',
 
Search WWH ::




Custom Search