Home >Database >Mysql Tutorial >How to Simulate SQL's LIKE Operator in MongoDB?

How to Simulate SQL's LIKE Operator in MongoDB?

Barbara Streisand
Barbara StreisandOriginal
2025-01-23 19:26:09182browse

How to Simulate SQL's LIKE Operator in MongoDB?

Replicating SQL's LIKE functionality in MongoDB

SQL's LIKE operator simplifies pattern-based searches. For example, finding all users with names containing "m" is easily done:

<code class="language-sql">SELECT * FROM users WHERE name LIKE '%m%';</code>

MongoDB, lacking a direct LIKE equivalent, leverages regular expressions for similar functionality. The MongoDB counterpart to the above SQL query is:

<code class="language-javascript">db.users.find({ name: /.*m.*/ });</code>

This uses a regular expression /.*m.*/ to locate any document where the name field contains "m" anywhere within the string. The . matches any character, * matches zero or more occurrences, and m is the literal character to search for.

A simpler, but less precise, alternative is:

<code class="language-javascript">db.users.find({ name: /m/ });</code>

This finds any name field containing at least one "m".

MongoDB's regular expression capabilities surpass SQL's LIKE operator in flexibility, enabling more intricate pattern matching. For comprehensive details on MongoDB regular expressions, consult the official MongoDB documentation and the MDN Web Docs on regular expressions. (Please replace https://www.php.cn/link/f84f4800d13741a98ddf9bc46e58355c and https://www.php.cn/link/a93dddc1fd67c3a6409fafb5801d7d50 with the actual links.)

The above is the detailed content of How to Simulate SQL's LIKE Operator 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