Reputation: 57
I am working on a python script to connect to mongodb and query a collection.
I want to find the values for key hp
that start with cdl
. This query successfully runs when I try through mongo shell but through my python script I see the error.
Do I need to have any escape characters ?
./pymongoconn.py
File "./pymongoconn.py", line 20
for response in conn.collection.find({"hp": /^cdl/},{"n":1 ,"hp":1 , "_id":0 , "rsid" :1, "v":1}):
^
SyntaxError: invalid syntax
Below is my query :
for response in conn.collection.find(
{"hp": /^cdl/},
{"n":1 ,"hp":1 , "_id":0 ,"rsid" :1, "v":1}
):
print (response)
Upvotes: 0
Views: 4643
Reputation:
I think your syntax is slightly wrong for a $regex
in pymongo.
Try:
conn.collection.find(
{"hp": {"$regex": "^cdl"}},
{"n":1 ,"hp":1 , "_id":0 ,"rsid" :1, "v":1}
)
You could also add in $option
into the $regex
. If you wanted case insensitive;
conn.collection.find({"hp": {"$regex": "^cdl", "$options": "i"}}))
You have all the options available as per mongo $regex
, here
Upvotes: 1
Reputation: 14449
Use re.compile:
import re
cdl= re.compile("^cdl", re.IGNORECASE)
for response in conn.collection.find(
{"hp": cdl},
{"n":1 ,"hp":1 , "_id":0 ,"rsid" :1, "v":1}
):
print (response)
Upvotes: 2