I need to translate some MySQL to mongodb. I have a MySQL query with multiple regular expression matches on one column. Is it possible to do the same thing with mongodb?
SELECT * FROM table WHERE column1 REGEXP r1 AND column1 REGEXP r2 AND colum1 REGEXP r3;
With pymongo I can perform regex s开发者_运维百科earches with single regex like so:
regex1 = re.compile(r1)
db.collection.find({"column1":regex1})
or
db.collection.find({"column1":{"$regex":"r1"}})
How do I add multiple regexes on column1?
These do not work:
{"column1":regex1,"column1":regex2}
{"column1":{"$regex":"r1","$regex":"r2"}}
{"column1":[regex1,regex2]}
{"column1":{"$regex":["r1","r2"]}}
db.collection.find({"column1": {"$all": [re.compile("r1"), re.compile("r2")]}})
Also take a look at future $and operator.
BTW unless your regexp is prefix-like (/^text/
) the index won't be used.
精彩评论