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>
Example: Find "m" in a string
Consider the following SQL query:
<code>SELECT * FROM users WHERE name LIKE '%m%'</code>
In MongoDB, the equivalent query is:
<code>db.users.find({"name": /.*m.*/})</code>
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>
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>
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!