Database Reference
In-Depth Information
... {
... "Type" : "Laptop",
... "ItemNumber" : "3456TFS",
... "Status" : "In use",
... "Location" : {
... "Department" : "Development",
... "Building" : "2B",
... "Floor" : 12,
... "Desk" : 120103,
... "Owner" : "Walker, Jan"
... },
... "Tags" : ["Laptop","Development","In Use"]
... }]
>>> collection.insert(two)
[ObjectId('4c57234c4abffe0e0c000001'), ObjectId('4c57234c4abffe0e0c000002')]
Finding Your Data
PyMongo provides two functions for finding your data: find_one() , which finds a single document in your collection
that matches specified criteria; and find() , which can find multiple documents based on the supplied parameters
(if you do not specify any parameters, find() matches all documents in the collection). Let's look at some examples.
Finding a Single Document
As just mentioned, you use the find_one() function to find a single document. The function is similar to the
findOne() function in the MongoDB shell, so mastering how it works shouldn't present much of a challenge for you.
By default, this function will return the first document in your collection if it is executed without any parameters, as in
the following example:
>>> collection.find_one()
{
u'Status': u'In use',
u'Tags': [u'Laptop', u'Development', u'In Use'],
u'ItemNumber': u'1234EXD',
u'Location':{
u'Department': u'Development',
u'Building': u'2B',
u'Floor': 12,
u'Owner': u'Anderson, Thomas',
u'Desk': 120101
},
u'_id': ObjectId('4c57207b4abffe0e0c000000'),
u'Type': u'Laptop'
}
You can specify additional parameters to ensure that the first document returned matches your query.
Every parameter used with the find() function can also be used for find_one() as well, although the limit
parameter will be ignored. The query parameters need to be written just as they would if you were defining them in
the shell; that is, you need to specify a key and its value (or a number of values). For instance, assume you want to find
 
Search WWH ::




Custom Search