无法在mongodb中的$ in运算符中使用正则表达式

Sai*_*Ram 4 regex mongodb

我正在尝试使用文档中提到的regexwith $in运算符,但我仍然无法获得值.

db.users.find({'profile.firstName':{$in:["/justin/i"]}}).count() = 0

但是当我这样使用的时候

db.users.find({'profile.firstName':{$in:["justin"]}}).count()=1

db.users.find({'profile.firstName':{$in:["Justin"]}}).count()=2

编辑问题

似乎我不清楚我将添加代码以便于理解的问题

我试图从一个不区分大小写的查询中获取文档列表.我认为用代码解释我的疑问会更好.

Meteor.users.find({'profile.firstName':{$in:[/justin/i,/helen/i]}}).count()

会给文件,其profile.firstNamejustin/Justin/JUSTIn/HElen/helen

但我怀疑如何给变量x=["sai","test","jacob",---etc]代替helen/justin

chr*_*dam 20

您需要使用RegExp对象包装数组中的元素,即

regex = [new RegExp("sai", "i"), new RegExp("test", "i"),...]

您可以使用该map()方法将RegExp包装器中的元素映射到新数组,然后可以在regex查询中使用该数组$in:

var x = ["sai","test","jacob","justin"],
    regex = x.map(function (e) { return new RegExp(e, "i"); });

db.users.find({"profile.firstName": { "$in": regex } });
Run Code Online (Sandbox Code Playgroud)

$in对于小型数组,使用可以相当有效,但对于大型列表则不太好,因为它将在索引中跳过以查找匹配的文档,或者如果没有要使用的索引则遍历整个集合.


除了在正则表达式中使用$ in之外,您还可以使用管道分隔的正则表达式模式和关键字列表,如下所示:

var x = ["sai","test","jacob","justin"],
    regex = x.join("|");

db.users.find({
    "profile.firstName": {
        "$regex": regex, 
        "$options": "i"
    } 
}).count;
Run Code Online (Sandbox Code Playgroud)

  • $in 和将正则表达式通过管道传输到其中都对我有用,但组合后的正则表达式速度快了 10 倍,使用 11 个正则表达式的数组并搜索 3.4K 文档的集合。时间从 5000 毫秒缩短到 50 毫秒。 (2认同)