0

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)

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.