How to query MongoDB with “like”?

后端 未结 30 2116
予麋鹿
予麋鹿 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:17

    That would have to be:

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

    or, similar:

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

    You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to Regexp's '.*'), not something that has "m" anchored to the beginning of the string.

    note: mongodb uses regular expressions which are more powerful than "LIKE" in sql. With regular expressions you can create any pattern that you imagine.

    For more info on regular expressions refer to this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

提交回复
热议问题