Home > Database > Mysql Tutorial > How Does MongoDB's Regular Expression Matching Compare to SQL's `LIKE` Operator?

How Does MongoDB's Regular Expression Matching Compare to SQL's `LIKE` Operator?

Susan Sarandon
Release: 2025-01-23 19:11:10
Original
579 people have browsed it

How Does MongoDB's Regular Expression Matching Compare to SQL's `LIKE` Operator?

Equivalent of SQL "LIKE" query in MongoDB

MongoDB provides a powerful way to query data using regular expressions. While SQL uses the "LIKE" operator, MongoDB uses regular expressions, which provides greater flexibility in pattern matching.

Query structure

To replicate the functionality of SQL "LIKE" queries in MongoDB, use the following syntax:

<code>db.collection.find({field: /pattern/})</code>
Copy after login

Example: Find "m" in a string

Consider the following SQL query:

<code>SELECT * FROM users WHERE name LIKE '%m%'</code>
Copy after login

In MongoDB, the equivalent query is:

<code>db.users.find({"name": /.*m.*/})</code>
Copy after login

This query searches documents where the "name" field contains "m" anywhere in the string.

Other syntax

Alternatively, you can use a simpler expression to achieve the same result:

<code>db.users.find({"name": /m/})</code>
Copy after login

However, it is important to note that this expression only matches strings starting with "m".

Advantages of regular expressions

MongoDB’s regular expressions provide advanced functionality beyond the SQL “LIKE” operator. They allow complex pattern matching, allowing you to define precise search criteria.

For example, you can exclude words that contain "m" but end with "c" using the following expression:

<code>db.users.find({"name": /^.*m.*[^c]$/})</code>
Copy after login

The above is the detailed content of How Does MongoDB's Regular Expression Matching Compare to SQL's `LIKE` Operator?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template