Querying with Regular Expressions in MongoDB

If you're familiar with SQL, you might be accustomed to using the LIKE operator to search for patterns in text. In MongoDB, you can achieve similar functionality using regular expressions.

Example SQL Query

In SQL, you might write a query like this to find users whose names contain the letter 'm':

SELECT * FROM users WHERE name LIKE '%m%';

Equivalent MongoDB Query

To perform the same operation in MongoDB, you can use the $regex operator within a query. Here's how you can do it:

db.users.find({ "name": /.*m.*/ });

Explanation:

  • The /.*m.*/ pattern is a regular expression that matches any string containing the letter 'm'.
  • The .* before and after 'm' allows for any characters to appear before or after 'm', effectively mimicking the % wildcard in SQL.

Case Sensitivity

By default, the regex search is case-sensitive. If you want to make it case-insensitive, you can add the i option:

db.users.find({ "name": /.*m.*/i });

Conclusion

Using regular expressions in MongoDB provides a powerful way to perform pattern matching similar to SQL's LIKE. This method is particularly useful for text searches within your documents.