简体   繁体   English

在Mongodb中使用Regex搜索查询

[英]Search query using Regex in Mongodb

I am trying to fetch results from mongodb using regular expressions. 我正在尝试使用正则表达式从mongodb获取结果。 For example, while searching for a username amitverma , I want to be able to get that result if i type amit in the searchbox. 例如,在搜索用户名amitverma ,如果我在搜索amitverma键入amit ,我希望能够得到该结果。

I have searched around the internet for a solution and everybody seems to have got it working by writing code like this: 我在互联网上搜索了一个解决方案,似乎每个人都可以通过编写如下代码来使其工作:

var searchterm = req.body.name;
        collection.find(
            { "username": new RegExp('/.*' + searchterm + '.*/') },
            [ 'username', 'status' ], 
            function(e, docs){
                console.log(e);
                console.log(docs);
                res.writeHead(200, {'content-type': 'text/json' });
                res.write( JSON.stringify({ 'docs' : docs }) );
                res.end('\n');
            }
        );

I still cannot get it to work. 我仍然无法正常工作。 It gives me an empty array. 它给了我一个空数组。 Also, after replaceing {username: searchterm} to { "username": new RegExp('/.*' + searchterm + '.*/') } , I can't even get results for the string amitverma which means this regex thing is failing. 另外,在将{username: searchterm}{ "username": new RegExp('/.*' + searchterm + '.*/') } ,我什至无法获得字符串amitverma结果,这意味着这是正则表达式失败了。

Try removing the slashes from the RegExp() constructor: 尝试从RegExp()构造函数中删除斜杠:

{ "username": new RegExp('.*' + searchterm + '.*') },

The slashes should not be there, unless you are searching for two literal forward slashes. 除非您要搜索两个文字正斜杠,否则斜杠不应存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM