简体   繁体   中英

pymongo query regex

I am trying to retrieve all stories where the images.path has the text "images123456.jpg" for example.

In my mongocompass, I am able to retrieve it using this

{$and: [{"images.path": {$exists: true}}, {"images.path": /.*images[1-9].*/}] }

In my python script, I tried to paste the query in the following.

client = MongoClient(HOST, PORT)
dbStuff = client['myDatabase']   
myCollection = dbStuff.story.with_options(codec_options=CodecOptions(tz_aware=True, tzinfo=pytz.timezone('Asia/Singapore'))) 
retrieved = myCollection .find({"$and": [{"images.path": {"$exists": True}}, {"images.path": '/.*images[1-9].*/'}] })
print retrieved.count() # Prints out 0

There is something wrong in the python script for

{"images.path": '/.*images[1-9].*/'}] }

part. How can i make the necessary changes?

/ is used as regular expression delimiter in some languages like JS. In Python you just write the contents of a regular expression as a string.

JS: /foo.*bar/

Python: r'foo.*bar'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM