Find substrings in PyMongo

I wanted to find substrings inside a field in MongoDB using PyMongo.

The following query works fine, and this is what I need:

db.collection.find({ "Animal": /cat|Dog/i}) 

However, if I try to pass the value /cat|Dog/i as a string in Python, this will not work.

Is there a way to replicate a request in PyMongo ?

Note: /cat|Dog/i - field value from another collection. It is in the shape of a "cat dog". Basically, I want to combine substrings in one field with substrings in another.

+5
source share
1 answer

You need to compile the regex pattern using the re.compile() function re.compile() object.

 import re pat = re.compile(r'cat|Dog', re.I) db.collection.find({ "Animal": {'$regex': pat}}) 
+6
source

Source: https://habr.com/ru/post/1236818/


All Articles