Mongodb – 使用$regex运算符查找包含数组中数值的所有文档

huangapple go评论71阅读模式
英文:

Mongodb - find all documents which contain value in array using $regex operator

问题

在我的Mongo数据库中执行搜索,找到所有包含特定字符串的文档。

代码的第一部分将用户输入按空格分割,然后将其推送到数组中。

代码的第二部分搜索数据库,查找数组中每个项与firstName字段之间的匹配项。

我尝试使用正则表达式运算符来忽略大小写,并查看每个元素是否在字段的任何位置包含;即,数组元素字符串"f"将产生与"frank""doofus"匹配,但不匹配"carlos"等。

以下是我的代码:

var string = 'carlos f sdf';
string = string.split(" ");
var stringArray = new Array();
for(var i = 0; i < string.length; i++){
   stringArray.push(string[i]);
}

User.find({firstName: { $regex: { $in: stringArray }, $options: 'i' }}).select("-password").then(user => console.log(user))

这是我遇到的错误:

UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ '$in': [ 'carlos', 'f', 'sdf' ] }" at path "firstName" for model "users"

有什么想法,我做错了什么?

英文:

Looking to perform a search in my Mongo database which will find all documents that contain a certain string.

The first part of the code splits the user input by spaces, then pushes it to an array.

The second part of the code searches the database to find a match between each item in the array and the firstName field.

I'm trying to use the regex operator to ignore case sensitivity and also see if each element is contained anywhere in the field; i.e. the array element string &quot;f&quot;, would yield a match for &quot;frank&quot;, &quot;doofus&quot;, but not &quot;carlos&quot; - etc.

Here is my code:

var string = &#39;carlos f sdf&#39;;
string = string.split(&quot; &quot;);
var stringArray = new Array();
for(var i =0; i &lt; string.length; i++){
   stringArray.push(string[i]);
}

User.find({firstName: { $regex: {$in: stringArray}, $options: &#39;i&#39;}}).select(&quot;-password&quot;).then(user=&gt;console.log(user))

And this is the error I'm getting:

>UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ '$in': [ 'carlos', 'f', 'sdf' ] }" at path "firstName" for model "users"

Any ideas what am I doing wrong?

答案1

得分: 1

我们可以使用"or"函数来获取结果:

User.find({
    "$or": [{
        firstName: { $regex: 'carlos', $options: 'i'}
    }, 
    {
        firstName: { $regex: 'f', $options: 'i'}
    },
    {
        firstName: { $regex: 'sdf', $options: 'i'}
    }]
});
英文:

We can use or function for getting result

User.find({
    &quot;$or&quot;: [{
        firstName: { $regex: &#39;carlos&#39;, $options: &#39;i&#39;}
    }, 
   {
        firstName: { $regex: &#39;f&#39;, $options: &#39;i&#39;}
    },
   {
        firstName: { $regex: &#39;sdf&#39;, $options: &#39;i&#39;}
    }]
});

答案2

得分: 0

你可以使用' | '作为正则表达式的'OR'运算符。

db.collection.find({ "firstName": { "$regex": "^carlos$|^f$|^sdf$", $options: "i" } })

上面的查询应该适用于你,如果你想匹配精确的值。

如果你想匹配包含给定字符串的文档,可以使用以下查询。

db.collection.find({ "firstName": { "$regex": "carlos|f|sdf", $options: "i" } })

至于你提到的动态长度输入,你只需要将所有这些字符串用'$|^'连接起来,然后一旦所有字符串都连接起来,你可以在开头加上'^'并在结尾加上'$'以实现精确匹配,如果要进行包含匹配,只需使用' | '运算符将所有字符串连接起来。

英文:

You can use '|' as an 'OR' operator for the regular expressions.

db.collection.find({ &quot;firstName&quot;: { &quot;$regex&quot;: &quot;^carlos$|^f$|^sdf$&quot;, $options: &quot;i&quot; } })

The above query should work for you if you want to match the exact values.

If you want to match for those documents which contain given strings then use the below query.

db.collection.find({ &quot;firstName&quot;: { &quot;$regex&quot;: &quot;carlos|f|sdf&quot;, $options: &quot;i&quot; } })

And as you asked about dynamic length input then you just have to Join all those string with '$|^' and once all the strings are joined you can append it with '$' and prepend it with '^' for the exact match in case of contain you just need to join all the string with '|' operator.

答案3

得分: 0

感谢大家的回复。以下是我解决问题的方法:

var string = req.params.postParams
string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
    stringArray.push(string[i]);
}
var regex = stringArray.map(function (e) { return new RegExp(e, "i"); });

User.find({firstName: { $in: regex }).select("-password").then(user=>console.log(user))
英文:

Thank you for the responses everyone. Below is how I solved the problem

var string = req.params.postParams
string = string.split(&quot; &quot;);
var stringArray = new Array();
for(var i =0; i &lt; string.length; i++){
    stringArray.push(string[i]);
}
var regex = stringArray.map(function (e) { return new RegExp(e, &quot;i&quot;); });

User.find({firstName: { $in: regex }).select(&quot;-password&quot;).then(user=&gt;console.log(user))

huangapple
  • 本文由 发表于 2020年1月6日 20:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定