Performing regex Queries with pymongo

Turns out regex searches are done a little differently in pymongo but is just as easy.

Regex is done as follows :

db.collectionname.find({'files':{'$regex':'^File'}})

This will match all documents that have a files property that has a item within that starts with File


If you want to include regular expression options (such as ignore case), try this:

import re
regx = re.compile("^foo", re.IGNORECASE)
db.users.find_one({"files": regx})

To avoid the double compilation you can use the bson regex wrapper that comes with PyMongo:

>>> regx = bson.regex.Regex('^foo')
>>> db.users.find_one({"files": regx})

Regex just stores the string without trying to compile it, so find_one can then detect the argument as a 'Regex' type and form the appropriate Mongo query.

I feel this way is slightly more Pythonic than the other top answer, e.g.:

>>> db.collectionname.find({'files':{'$regex':'^File'}})

It's worth reading up on the bson Regex documentation if you plan to use regex queries because there are some caveats.