Database Reference
In-Depth Information
Next, let's look at how to specify a query operator using the find() function. The methods used for this are
identical to the ones seen previously in the topic:
>>> for doc in collection.find({"Location.Owner" : "Walker, Jan"}):
... doc
...
{
u'Status': u'In use',
u'Tags': [u'Laptop', u'Development', u'In Use'],
u'ItemNumber': u'3456TFS',
u'Location': {
u'Department': u'Development',
u'Building': u'2B',
u'Floor': 12,
u'Owner': u'Walker, Jan',
u'Desk': 120103
},
u'_id': ObjectId('4c57234c4abffe0e0c000002'),
u'Type': u'Laptop'
}
Using Dot Notation
Dot notation is used to search for matching elements in an embedded object. The preceding snippet shows an
example of how to do this. When using this technique, you simply specify the key name for an item within the
embedded object to search for it, as in the following example:
>>> for doc in collection.find({"Location.Department" : "Development"}):
... doc
...
This example returns any document that has the Development department set. When searching for information
in a simple array (for instance, the tags applied), you just need to fill in any of the matching tags:
>>> for doc in collection.find({"Tags" : "Laptop"}):
... doc
...
Returning Fields
If your documents are relatively large, and you do not want to return all key/value information stored in a document,
you can include an additional parameter in the find() function to specify that only a certain set of fields need to be
returned using True , or kept hidden using False . You do this by providing the fields parameter, followed by a list of
field names after the search criteria. Note that outside of the _id field, you cannot mix True and False in a query.
The following example returns only the current owner's name, the item number, and the object ID (this will
always be returned, unless you explicitly tell MongoDB not to return it):
>>> for doc in collection.find({'Status' : 'In use'}, fields={'ItemNumber' : True, 'Location.Owner'
: True}):
... doc
...
 
Search WWH ::




Custom Search