0

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?

Ninja Dude
  • 1,332
  • 4
  • 27
  • 54
  • 1
    I found the same question on SO https://stackoverflow.com/questions/3483318/performing-regex-queries-with-pymongo – shotasenga Jul 06 '20 at 08:36
  • It is explained in PyMongo [docs](https://pymongo.readthedocs.io/en/stable/api/bson/regex.html) – prasad_ Jul 06 '20 at 08:40
  • try this, ```myCollection.find({"$and": [{"images.path": {"$exists": True}}, {"images.path": {'$regex': '.*images[1-9].*'}}]})``` – sushanth Jul 06 '20 at 08:42

1 Answers1

0

/ 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'

D. SM
  • 13,584
  • 3
  • 12
  • 21