开发者

Performing multiple regex matches to same index with pymongo

开发者 https://www.devze.com 2023-03-11 04:12 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消