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

mongodb regex not
mongodb string replace regex
mongodb regex search on integer value
mongodb java regex example
mongodb text search regex
how to use wildcard in mongodb query
mongodb regex search in array
mongodb regex not working

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


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

Use variable with regex to find data in mongodb (Meteor app , fetch();. but, when I want to combine variable with regex in MongoDB query it returns nothing, what am I doing wrong: Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.


I was having same problem with my title and after lots of searching, i found this answer Here,

var search = 'Joe';
db.users.find(name: /^search/)
db.users.find(name: {$regex: /^search/});
db.users.find(name: {$regex: "/^" + search + "/"});

The queries above won’t return anything. The solution to this little problem is quite simple:

db.users.find(name: new RegExp(search)) //For substring search, case sensitive. 
db.users.find(name: new RegExp('^' + search + '$')) //For exact search, case sensitive
db.users.find(name: new RegExp(search, ‘i')) //For substring search, case insensitive
db.users.find(name: new RegExp('^' +search + '$', 'i')); //For exact search, case insensitive

Other flags or properties can be added base on reference here

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 egI have constructed a simple regex as 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


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

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

It is not allowed to put $regex in $in operator according to the manual.

If you want to put regular expression object in $in operator, you have to use JavaScript regular expression object, for example:

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

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

$regex, Index Use¶. For case sensitive regular expression queries, if an index exists for the field, then MongoDB matches the regular expression against the values in the​  • We can create database indexes on the document fields so that the MongoDB query will make use of these indexed values to match the regular expression. This makes the search and the data retrieval from the collection very fast as compared to the traditional regular expression scanning that scan the collection as a whole.


Use the following code to use dynamic value in regex with or operations

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

MongoDB Regular Expression (Regex) with Examples, Regular expressions are used for pattern matching, which is is being used to print each document which is returned by the query in a better  How can we use a Regular Expression in an Array? We can use the concept of regular expression in an array. Regular expression is very important when we are working with the tags. If you want to search all the tags with ” my new post” the following query will find all the Post having tags “my new post” and return us a result. Query:


How to Use a SQL LIKE Statement in MongoDB, Searching for Word Similarities Using Regex. Now that we are using .find() to query our collection, we can actually modify our syntax ever so slightly and begin​  Regular expressions are used for pattern matching, which is basically for findings strings within documents. Sometimes when retrieving documents in a collection, you may not know exactly what the exact Field value to search for. Hence, one can use regular expressions to assist in retrieving data based on pattern matching search values.


MongoDB Evaluation Query operator - $regex, In MongoDB, matching the pattern can do by using regular expression objects or using the $regex operator. Our database name is 'myinfo' and  Aggregation expressions can use both user-defined and system variables. Variables can hold any BSON type data. To access the value of the variable, prefix the variable name with double dollar signs ($$); i.e. "$$<variable>". If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$$<variable>.<field>".


Using variable regex with MongoDB query in Node.JS, js application with MongoDB integration when I came across this little problem with Regular expressions and MongoDB calls. The following code  Using variable regex with MongoDB query in Node.JS. Posted on February 11, 2015 by GM. Extending this topic here by Ivan Breet a bit more. I was busy writing a Node