我需要将一些 MySQL 转换为 mongodb。我有一个 MySQL 查询,在一列上有多个正则表达式匹配项。是否可以用 mongodb 做同样的事情?
SELECT * FROM table WHERE column1 REGEXP r1 AND column1 REGEXP r2 AND colum1 REGEXP r3;
借助 pymongo,我可以像这样使用单个正则表达式执行正则表达式搜索:
regex1 = re.compile(r1)
db.collection.find({"column1":regex1})
或
db.collection.find({"column1":{"$regex":"r1"}})
如何在 column1 上添加多个正则表达式?
这些不起作用:
{"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")]}})
也看看 future $and operator .
顺便说一句,除非你的正则表达式是前缀式的 (/^text/
) 索引 won't be used .
关于python - 使用 pymongo 对同一索引执行多个正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6264263/