【问题标题】:unable to use regex in $in operator in mongodb无法在 mongodb 的 $in 运算符中使用正则表达式
【发布时间】:2016-04-30 01:44:27
【问题描述】:

我正在尝试将regex$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

【问题讨论】:

    标签: regex mongodb


    【解决方案1】:

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

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

    您可以使用 map() 方法将带有 RegExp 包装器的数组中的元素映射到一个新数组,然后您可以通过 $in

    var x = ["sai","test","jacob","justin"],
        regex = x.map(function (e) { return new RegExp(e, "i"); });
    
    db.users.find({"profile.firstName": { "$in": regex } });
    

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


    除了using the $in with the regular expression,您还可以使用管道分隔的正则表达式模式和关键字列表,如下所示:

    var x = ["sai","test","jacob","justin"],
        regex = x.join("|");
    
    db.users.find({
        "profile.firstName": {
            "$regex": regex, 
            "$options": "i"
        } 
    }).count;
    

    【讨论】:

    • $in 和将正则表达式连接到一个中都对我有用,但是组合正则表达式的速度提高了 10 倍,其中包含 11 个正则表达式并搜索 3.4K 文档的集合。时间从 5000 毫秒变为 50 毫秒。
    • 对于左锚定(以^ 开头)、区分大小写(无i 选项)的表达式,采用$in 方法将使用已配置的索引,因此是最佳的,对吗?
    【解决方案2】:

    尝试这样做

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

    您将正则表达式作为字符串传递。

    通常你应该一次只问一个问题,这样问题就集中在一个特定的问题上

    嗯,你可以直接传过去,像这样

    // Here I am creating regex for all the elements in array
    let myRegex = new RegExp(myArray.join('|'), i) 
    and then I can pass this regex
    db.users.find({'profile.firstName':{$in: myRegex}}).count() = 0
    

    【讨论】:

    • 嘿,感谢您的解决方案,但请检查一下问题,因为我已经添加了更多内容。
    • 但这不会使查询区分大小写
    • 哈哈哈对不起兄弟,我可能错过了通知,因为最近回答了很多问题
    猜你喜欢
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2012-10-30
    • 1970-01-01
    • 2023-01-02
    • 2019-05-03
    相关资源
    最近更新 更多