monicak
monicak

Reputation: 57

pymongo : find query with regex

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

Answers (2)

user9251303
user9251303

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

anhlc
anhlc

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

Related Questions