Database Reference
In-Depth Information
u'_id': ObjectId('4c5dda114abffe0f34000000'),
u'Type': u'Desktop'
}
}
Let's look at another example. This time, you will use
find_and_modify()
to remove a document; in this case, the
output will show which document was removed:
>>> collection.find_and_modify(query={'Type' : 'Desktop'},
... sort={'ItemNumber' : -1}, remove=True)
{
u'ok': 1.0,
u'value': {
u'Status': u'In use',
u'Tags': [u'Desktop', u'In use', u'Marketing', u'Warranty'],
u'ItemNumber': u'4532FOO',
u'Location': {
u'Department': u'Marketing',
u'Building': u'2B',
u'Owner': u'Martin, Lisa',
u'Desknumber': 131131
},
u'_id': ObjectId('4c5ddbe24abffe0f34000001'),
u'Type': u'Desktop'
}
}
Deleting Data
In most cases, you will use the Python driver to add or modify your data. However, it's also important to understand
how to delete data. The Python driver provides several methods for deleting data. First, you can use the
remove()
function to delete a single document from a collection. Second, you can use the
drop()
or
drop_collection()
function to delete an entire collection. Finally, you can use the
drop_database()
function to drop an entire database.
(It seems unlikely you'll be using this function frequently!)
Nevertheless, we will take a closer look at each of these functions, looking at examples for all of them.
Let's begin by looking at the
remove()
function. This function allows you to specify an argument as a parameter
that will be used to find and delete any matching documents in your current collection. In this example, you use the
remove()
function to remove each document that has a key/value pair of
"Status" : "In use"
; afterward, you use
the
find_one()
function to confirm the results:
>>> collection.remove({"Status" : "In use"})
>>> collection.find_one({"Status" : "In use"})
>>>
You need to be careful what kind of criteria you specify with this function. Usually, you should execute a
find()
first, so you can see exactly which documents will be removed. Alternatively, you can use the
ObjectId
to
remove an item.