Using variable regex with MongoDB query in Node.JS

Extending this topic here by Ivan Breet a bit more.

I was busy writing a Node.js application with MongoDB integration when I came across this little problem with Regular expressions and MongoDB calls. The following code will just return nothing:

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
This entry was posted in MongoDB, Node.JS and tagged , , . Bookmark the permalink.

5 Responses to Using variable regex with MongoDB query in Node.JS

  1. jason's avatar jasonmfry says:

    I appreciate this post, it comes up on a google search, and it’s exactly what I was looking for!

  2. HamzaM's avatar HamzaM says:

    I really appreciate this post. Really helped me out. I could’nt find any solution anywhere as.

  3. RD's avatar RD says:

    From where you learn this?
    Really helpful

  4. EJ's avatar EJ says:

    What if there are special symbold like ‘+’, ‘-‘ in search string, which i am getting from frontend.
    How to perform regex search for speacial symbols

  5. Pingback: How can I use a regex variable in a query for MongoDB – w3toppers.com

Leave a comment