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 sensitivedb.users.find(name: new RegExp(search, ‘i')) //For substring search, case insensitivedb.users.find(name: new RegExp('^' +search + '$', 'i')); //For exact search, case insensitiveOther flags or properties can be added base on reference here
I appreciate this post, it comes up on a google search, and it’s exactly what I was looking for!
I really appreciate this post. Really helped me out. I could’nt find any solution anywhere as.
From where you learn this?
Really helpful
What if there are special symbold like ‘+’, ‘-‘ in search string, which i am getting from frontend.
How to perform regex search for speacial symbols
Pingback: How can I use a regex variable in a query for MongoDB – w3toppers.com