javascript – MongoDB检查列表中的多个正则表达式匹配以进行自由文本搜索

我正在设置一个mongoDB数据库,允许(简单)使用多键进行关键字搜索,如推荐的
here.记录看起来也类似:

{ title: { title: "A river runs through", _keywords: ["a","river","runs","through"] ) , ... }

我使用nodejs服务器端,所以我使用的是javascript.以下查询将匹配(这是在mongo终端中运行):

> db.torrents_sorted.find({'title._keywords' : {"$all" : ["river","the"]} }).count()
210

但是,这些不是:

> db.torrents_sorted.find({'title._keywords' : {"$all" : ["/river/i","/the/i"]} }).count()
0

> db.torrents_sorted.find({'title._keywords' : {"$all" : [{ "$regex" : "river", "$options" : "i" },{ "$regex" : "the", "$options" : "i" }]} }).count()
0

使用单个正则表达式(不使用$和或$all)匹配:

db.torrents_sorted.find({‘title._keywords’ : { “$regex” : “river”, “$options” : “i” } }).count()
1461

有趣的是,使用python和pymongo编译正则表达式确实有效:

>>> db.torrents_sorted.find({'title._keywords': { '$all': [re.compile('river'), re.compile('the')]}}).count();
236

我不一定在寻找使用正则表达式的解决方案,但是要求关键字在较短的字符串上匹配,因此“riv”匹配“river”,这似乎是正则表达式(或sql中的LIKE)的理想选择.

我的下一个想法是尝试传入一个javascript函数,在列表上执行正则表达式匹配,或者可能为每个正则表达式传递一个单独的函数(这似乎是尖叫黑客攻击我:),虽然我猜这将是速度慢,性能非常重要.

最佳答案 您可能想要使用$和运算符.

点赞