我正在尝试使用文档中提到的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.firstName
为justin/Justin/JUSTIn/HElen/helen
但我怀疑如何使用变量x=["sai","test","jacob",---etc]
代替helen/justin
答案 0 :(得分:16)
您需要使用 RegExp
对象包装数组中的元素,即
regex = [new RegExp("sai", "i"), new RegExp("test", "i"),...]
您可以使用 map()
方法将数组中的元素与RegExp包装器映射到新数组,然后可以在 {{的正则表达式查询中使用该数组3}} 强>:
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;
答案 1 :(得分: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