Database Reference
In-Depth Information
After you load the module, you can specify the regular expression query in the value field of your search criteria.
The following example shows how to search for any document where ItemNumber has a value that contains a 4
(for the sake of keeping things simple, this example returns only the values in ItemNumber) :
>>> for doc in collection.find({'ItemNumber' : re.compile('4')}, {'ItemNumber' : True}):
... doc
...
{u'ItemNumber': u'1234EXD', u'_id': ObjectId('4c57207b4abffe0e0c000000')}
{u'ItemNumber': u'2345FDX', u'_id': ObjectId('4c57234c4abffe0e0c000001')}
{u'ItemNumber': u'2345FDX', u'_id': ObjectId('4c592eb84abffe0e0c000004')}
{u'ItemNumber': u'3456TFS', u'_id': ObjectId('4c57234c4abffe0e0c000002')}
You can further define a regular expression. At this stage, your query is case-sensitive, and it will match any
document that has a 4 in the value of ItemNumber , regardless of its position. However, assume you want to find
a document where the value of ItemNumber ends with FS , is preceded by an unknown value, and can contain no
additional data after the FS :
>>> for doc in collection.find({'ItemNumber' : re.compile('.FS$')},fields={'ItemNumber' : True}):
... doc
...
{u'ItemNumber': u'3456TFS', u'_id': ObjectId('4c57234c4abffe0e0c000002')}
You can also use find() to search for information in a case-insensitive way, but first you must add another
function, as in this example:
>>> for doc in collection.find({'Location.Owner' : re.compile('^anderson. ', re.IGNORECASE)},
... fields={'ItemNumber' : True, 'Location.Owner' : True}):
... doc
...
{
u'ItemNumber': u'1234EXD',
u'_id': ObjectId('4c57207b4abffe0e0c000000'),
u'Location': {
u'Owner': u'Anderson, Thomas'
}
}
Regular expressions can be an extremely powerful tool, as long as you utilize them properly. For more details on
how the re module works and the functions it includes, please refer to the module's official documentation at
http://docs.python.org/library/re.html .
Modifying the Data
So far you've learned how to use conditional operators and regular expressions in Python to query for information in
your database. In the next section, we'll examine how to use Python to modify the existing data in your collections.
We can use Python to accomplish this task in several different ways. The upcoming sections will build on the previously
used query operators to find the documents that should match your modifications. In a couple of cases, you may need
to skip back to earlier parts of this chapter to brush up on particular aspects of using query operators—but that's a
normal part of the learning process, and it will reinforce the lessons taught so far.
 
 
Search WWH ::




Custom Search