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

I would like to make a MongoDB query for documents based on the regex expression that I am constructing. For example, for example, I constructed a simple regular expression as follows: this is a combination of a random letter and a random number for 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 tried various combinations for regex variable, for example

 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() 

No, it seems to work. However, when I write the actual regular expression, I get entries, for example.

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

Any help would be appreciated.

Thanks ganesh

+5
source share
3 answers

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

 var stream = collection.find({"FirstName": new RegExp(val)}).stream(); 
+14
source

If you want to use the variable val as a parameter of the request part, you can use $ regex , for example:

 collection.find({"FirstName": {$regex:val}}) 

It is not permitted to put $ regex in the $ in statement according to the manual.

If you want to place the regular expression object in the $ in operator, you need to use the JavaScript regular expression object, for example:

 collection.find({"FirstName": {$in: [/abc/, /123/]}}) 

By the way, val in /val/ is a constant string, not a variable, as you defined above.

0
source

Use the following code to use a dynamic value in a regular expression with or operations

 {$match: { $or: [{ 'title': { $regex: request.query.val, $options: 'i'} }, { 'skills_required': { $regex: request.query.val, $options: 'i'} }] }}, 
0
source

Source: https://habr.com/ru/post/1206053/


All Articles