使用pymongo对同一索引执行多个正则匹配

1 投票
1 回答
1160 浏览
提问于 2025-04-16 19:06

我需要把一些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"]}}

1 个回答

6
db.collection.find({"column1": {"$all": [re.compile("r1"), re.compile("r2")]}})

另外,看看将来的 $and 操作符

顺便提一下,除非你的正则表达式是前缀类型的(比如 /^text/),否则索引 是不会被使用的。

撰写回答