Search code examples
sqlmongodbmongodb-querysql-like

How to query MongoDB with "like"


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

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

How can I achieve the same in MongoDB? I can't find an operator for like in the documentation.


Solution

  • 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 regular expressions' '.*'), not something that has "m" anchored to the beginning of the string.

    Note: MongoDB uses regular expressions (see docs) which are more powerful than "LIKE" in SQL. With regular expressions you can create any pattern that you imagine.

    For more information on regular expressions, refer to Regular expressions (MDN).