MongoDB / PyMongo: how to "avoid" parameters in regex search?

I am using pymongo and want to search for elements starting with a specific sequence of characters. I could implement this as follows:

items = collection.find({ 'key': '/^text/' }) 

This should work, but what if text is a variable? I could do something like:

 items = collection.find({ 'key': '/^' + variable + '/' }) 

But now, if the text in variable contains any characters with a special regular expression value (for example, $ ), the query no longer behaves as expected. Is there a way to do parameter binding? Do I need to sanitize a variable own? Is it possible to do this?

Thanks!

+6
source share
2 answers

You must programmatically create a regix. So either:

 import re regex = re.compile('^' + re.escape(variable)) items = collection.find({ 'key': regex }) 

OR

 items = collection.find({'key': { '$regex': '^' + re.escape(variable) }}) 

Note that the code uses re.escape to avoid a string if it contains special characters.

+7
source

Here is the concept: you have to use regex

 items = collection.find({ 'key' : { $regex : yourRegex } }) 
-1
source

All Articles