Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a regex variable in a query for MongoDB

I would like to make query MongoDB for documents based on a regex expression that I contruct. For e.g I have constructed a simple regex as follows that is a combination of a random letter and a random number for in Nodejs

var randnum = Math.floor((Math.random() * 10) + 1); var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z']; var randletter = alpha[Math.floor(Math.random() * alpha.length)]; var val = randletter + randnum + '.*; 

I have tried various combinations for the regex variable like

var stream = collection.find({"FirstName": /val/).stream(); && var stream = collection.find({"FirstName": /$val/).stream(); && var stream = collection.find({"FirstName": {$in : [{$regex:val}]}}).stream() && var stream = collection.find({"FirstName": {$in : [{$regex:$val}]}}).stream() 

None o it seem to work. However when I write the actual regex I get the records for e.g.

var stream = collection.find({"FirstName": /J.*/).stream(); 

Any help will be appreciated.

Thanks Ganesh

like image 911
Tinniam V. Ganesh Avatar asked Nov 02 '14 13:11

Tinniam V. Ganesh


People also ask

Can regex use MongoDB?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression. Case insensitivity to match upper and lower cases.

How do I search for a regular expression in MongoDB?

Regular Expressions are frequently used in all languages to search for a pattern or word in any string. MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language.

What is regex in mongoose?

Regular expression or Regex is a very important part of programming. It is usually used to find a pattern in a string.

How do I use $in in MongoDB?

MongoDB provides different types of comparison query operators and $in operator is one of them. This operator is used to select those documents where the value of the field is equal to any of the given value in the array.


Video Answer


1 Answers

You need to create a regular expression object from the string using the RegExp constructor as the /.../ syntax is only for use with literals.

var stream = collection.find({"FirstName": new RegExp(val)}).stream(); 
like image 164
JohnnyHK Avatar answered Sep 21 '22 08:09

JohnnyHK