Quantcast
Channel: How to query MongoDB with "like" - Stack Overflow
Viewing all articles
Browse latest Browse all 48

Answer by Ezequias Dinella for How to query MongoDB with "like"?

$
0
0

You can query with a regular expression:

db.users.find({"name": /m/});

If the string is coming from the user, maybe you want to escape the string before using it. This will prevent literal chars from the user to be interpreted as regex tokens.

For example, searching the string "A."will also match"AB" if not escaped.You can use a simple replace to escape your string before using it. I made it a function for reusing:

function textLike(str) {  var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');  return new RegExp(escaped, 'i');}

So now, the string becomes a case-insensitive pattern matching also the literal dot. Example:

>  textLike('A.');<  /A\./i

Now we are ready to generate the regular expression on the go:

db.users.find({ "name": textLike("m") });

Viewing all articles
Browse latest Browse all 48

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>