Home >Database >Mysql Tutorial >How to Replicate SQL's 'LIKE' Query Functionality in MongoDB?

How to Replicate SQL's 'LIKE' Query Functionality in MongoDB?

DDD
DDDOriginal
2025-01-23 19:22:10687browse

How to Replicate SQL's

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn