[英]unable to use regex in $in operator in mongodb
我正在尝试使用文档中提到的$in
运算符的regex
,但我仍然无法获得该值。
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.firstName
为justin/Justin/JUSTIn/HElen/helen
但我怀疑如何给变量x=["sai","test","jacob",---etc]
代替helen/justin
您需要使用RegExp
对象包装数组中的元素,即
regex = [new RegExp("sai", "i"), new RegExp("test", "i"),...]
您可以使用map()
方法将数组中的元素与RegExp包装器映射到一个新数组,然后您可以在带有$in
的正则表达式查询中使用$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
对于小型数组可能相当有效,但对于大型列表则不太好,因为它将在索引中跳过以查找匹配的文档,或者如果没有要使用的索引则遍历整个集合。
除了在正则表达式中使用$ in之外,您还可以使用管道分隔的正则表达式模式和关键字列表,如下所示:
var x = ["sai","test","jacob","justin"],
regex = x.join("|");
db.users.find({
"profile.firstName": {
"$regex": regex,
"$options": "i"
}
}).count;
试着这样做
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.