Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 475
Freewind Avatar asked Jul 22 '10 03:07

Freewind


People also ask

Can I use regex in MongoDB query?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression. Case insensitivity to match upper and lower cases.

How do I match a string in MongoDB?

MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.


1 Answers

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 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).

like image 115
Kyle H Avatar answered Sep 20 '22 09:09

Kyle H