How to query MongoDB with “like”?

后端 未结 30 2178
予麋鹿
予麋鹿 2020-11-21 05:51

I want to query something with SQL\'s like query:

SELECT * FROM users  WHERE name LIKE \'%m%\'

How to do I achieve the same in

30条回答
  •  故里飘歌
    2020-11-21 06:21

    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") });
    

提交回复
热议问题