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
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.
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.
Regular expression or Regex is a very important part of programming. It is usually used to find a pattern in a string.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With