无法在 mongodb 的 $in 运算符中使用正则表达式 [英] unable to use regex in $in operator in mongodb

查看:96
本文介绍了无法在 mongodb 的 $in 运算符中使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 regex 与文档中提到的 $in 运算符一起使用,但我仍然无法获取该值.

I am trying to use the regex with $in operator as mentioned in the docs but I am still unable to get the value.

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

编辑的问题

好像我对这个问题不太清楚我会添加代码以便于理解

seems like I am not clear with the question I will add the code for easy understanding

我正在尝试从不区分大小写的查询中获取文档列表.我认为最好用代码来解释我的疑问.

I am trying to get the list of documents from a query which is case insensitive.I think it better to explain my doubt with code.

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

将给出profile.firstNamejustin/Justin/JUSTIn/HElen/helen

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

but my doubt how to give the variable x=["sai","test","jacob",---etc] in place of helen/justin

推荐答案

您需要使用 RegExp 对象即

You need to wrap the elements in the array with the RegExp object i.e.

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

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

You can use the map() method to map the elements in the array with the RegExp wrappers to a new array that you can then use in the regex query with $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 $in can be fairly efficient with small arrays but not so well with huge lists since it will skip around in the index to find the matching documents, or walk through the whole collection if there isn't an index to use.

此外 将 $in 与正则表达式一起使用,您可以使用管道分隔的正则表达式模式和关键字列表,如下所示:

Besides using the $in with the regular expression, you could use a pipe-delimited regex pattern with the keywords list like this:

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

db.users.find({
    "profile.firstName": {
        "$regex": regex, 
        "$options": "i"
    } 
}).count;

这篇关于无法在 mongodb 的 $in 运算符中使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆