Database Reference
In-Depth Information
This operator takes only one additional value; however, it's also good to know that you can combine $addToSet
with the $each operator. Let's look at two examples. First, let's perform the update using the $addToSet operator on
any object matching "Type : Chair" and then check whether all went well using the find_one() function:
>>> collection.update({"Type" : "Chair"}, {"$addToSet" : {"Tags" : "Warranty"} }, multi = True)
>>> collection.find_one({"Type" : "Chair"}, {"Tags" : "True"})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'Chair', u'In use', u'Marketing', u'Warranty']
}
You can also use the $each statement to add multiple tags. Note that you perform this search using a regular
expression. Also, one of the tags in the list has been previously added; fortunately, it won't be added again, because
this is what $addToSet specifically prevents:
// Use the $each operator to add multiple tags, including one that was already added
>>> collection.update({"Type" : "Chair", "Location.Owner" : re.compile("^Martin,")},
... {"$addToSet" : { "Tags" : {"$each" : ["Martin","Warranty","Chair","In use"] } } } )
Now it's time to check whether all went well; specifically, you want to verify that the duplicate Warranty tag has
not been added again:
>>> collection.find_one({"Type" : "Chair", "Location.Owner" : re.compile("^Martin,")},
fields={"Tags" : True})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'Chair', u'In use', u'Marketing', u'Warranty', u'Martin']
}
Removing an Element from an Array with $pop
So far, you've seen how to use the update() function to add values to an existing document. Now let's turn this around
and look at how to remove data instead. We'll begin with the $pop operator.
This operator allows you to delete either the first or the last value from an array, but nothing in between.
The following example removes the first value in the Tags array from the first document it finds that matches the
"Type" : "Chair" criterion; the example then uses the find_one() command to confirm that all went well with
the update:
>>> collection.update({"Type" : "Chair"}, {"$pop" : {"Tags" : -1}})
>>> collection.find_one({"Type" : "Chair"}, fields={"Tags" : True})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'In use', u'Marketing', u'Warranty', u'Martin']
}
Giving the Tags array a positive value instead removes the last occurrence in an array, as in the following example:
>>> collection.update({"Type" : "Chair"}, {"$pop" : {"Tags" : 1}})
 
Search WWH ::




Custom Search