Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing regex queries with PyMongo

People also ask

Can I use regex in MongoDB query?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression. Case insensitivity to match upper and lower cases.

Does PyMongo support async?

The only async framework that PyMongo fully supports is Gevent. Currently there is no great way to use PyMongo in conjunction with Tornado or Twisted. PyMongo provides built-in connection pooling, so some of the benefits of those frameworks can be achieved just by writing multi-threaded code that shares a Connection.


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})

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


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.


The solution of re doesn't use the index at all. You should use commands like:

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

( I cannot comment below their replies, so I reply here )