Database Reference
In-Depth Information
Next, execute the
find_one()
function again to confirm that all went well:
>>> collection.find_one({"Type" : "Chair"}, fields={"Tags" : True})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'In use', u'Marketing', u'Warranty']
}
Removing a Specific Value with $pull
The
$pull
operator lets you remove each occurrence of a specific value from an array, regardless of how many times
the value occurs; as long as the value is the same, it will be removed.
Let's look at an example. Begin by using the
$push
operator to add identical tags with the value
Double
to the
Tags
array:
>>> collection.update({"Type" : "Chair"}, {"$push" : {"Tags" : "Double"} }, multi = False )
>>> collection.update({"Type" : "Chair"}, {"$push" : {"Tags" : "Double"} }, multi = False )
Next, ensure that the tag was added twice, by executing the
find_one()
command. Once you confirm that the tag
exists twice, use the
$pull
operator to remove both instances of the tag:
>>> collection.find_one({"Type" : "Chair"}, fields={"Tags" : True})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'In use', u'Marketing', u'Warranty', u'Double', u'Double']
}
>>> collection.update({"Type" : "Chair"}, {"$pull" : {"Tags" : "Double"} }, multi = False)
To confirm that all went well, execute the
find_one()
command again, this time making sure that the result no
longer lists the
Double
tag:
>>> collection.find_one({"Type" : "Chair"}, fields={"Tags" : True})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'In use', u'Marketing', u'Warranty']
}
You can use the
$pullAll
operator to perform the same action; the difference from
$pull
is that
$pullAll
lets
you remove multiple tags. Again, let's look at an example. First, you need to add multiple items into the
Tags
array
again and confirm that they have been added:
>>> collection.update({"Type" : "Chair"}, {"$addToSet" : { "Tags" : {"$each" : ["Bacon","Spam"] } }
} )
>>> collection.find_one({"Type" : "Chair"}, fields={"Tags" : True})
{
u'_id': ObjectId('4c5973554abffe0e0c000005'),
u'Tags': [u'In use', u'Marketing', u'Warranty', u'Bacon', u'Spam']
}