Home >Database >Mysql Tutorial >How to Replicate SQL's 'LIKE' Query Functionality in MongoDB?
MongoDB's Equivalent to SQL's LIKE Clause
SQL's LIKE
operator simplifies pattern-based string searches. MongoDB offers similar functionality using regular expressions.
Using Regular Expressions for Pattern Matching:
To mimic SQL's LIKE
, employ MongoDB's regular expression operator. For instance, to find strings containing "m":
<code class="language-javascript">/.*m.*/</code>
Here, .
matches any character, *
matches zero or more occurrences. This expression finds "m" anywhere within the string.
Example Query:
To retrieve all users with names including "m":
<code class="language-javascript">db.users.find({ name: /.*m.*/ })</code>
Simplified Approach (for simple cases):
For basic "contains" searches, a simpler regex suffices:
<code class="language-javascript">/m/</code>
Important Note:
MongoDB's regular expressions are more versatile than SQL's LIKE
. They allow for sophisticated and precise pattern definitions.
Further Reading:
The above is the detailed content of How to Replicate SQL's 'LIKE' Query Functionality in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!