PyMongo .find() Special Characters
<p>So I have set up a database in MongoDB and a majority of documents contain a special code which can begin with a * and finish with a #. When I use the following query on the MongoDb command line, it works fine but when I try to use it in a python script, it doesn't work.</p>

<pre><code>cursor = collect.find({$and:[{"key":/.*\*.*/},{"key":/.*\#.*/}]})
</code></pre>

<p>I think the problem lies with the # in the query but when I wrap it in " ", it doesn't work.</p>

<pre><code>cursor = collect.find({'$and':[{"key":'/.*\*.*/'},{"key":'/.*\#.*/'}]})
</code></pre>

<p>Please note that I put ' ' around $and and the first expression to match because syntax errors appear when I attempt to run it.</p>

<p>Thanks</p>

<p>If you want to query using a regular expression, then you have to create a Python regular expression object. Note that in this case the string should not be surrounded by <code>//</code>.</p>

<pre><code>import re
cursor = collect.find({'$and':[{"key":re.compile('.*\*.*')},{"key":re.compile('.*\#.*')}]})
</code></pre>

<p>Alternatively, you can use the <code>$regex</code> operator</p>

<pre><code>cursor = collect.find({'$and':[{"key": {"$regex": '.*\*.*'}},{"key": {"$regex": '.*\#.*'}}]})
</code></pre>

python mongodb pymongo