How to Use Regular Expressions in MongoDB

Introduction

When you’re querying text fields there’s no more powerful tool than regular expressions. Although they can get extremely complex, they are unbelievably powerful and super flexible. If you need to generate complicated text queries that aren’t just exact matches then you’ll probably want to look into regular expressions. In this article we’ll take a look at the basic syntax of a query in MongoDB using regular expressions.

Note: There are so many syntax details to regular expressions so we won’t delve too deep into that but we hope to give you just enough examples and resources to get you headed in the right direction to creating the query you need.

Prerequisites

  • You should have MongoDB installed and running
    • You can do this with a mongod command
  • You should have access to the MongoDB command line
    • You can get access to the command line be executing the mongo command while MongoDB is running.
  • Although it’s not required it’s helpful to brush up on regular expression syntax because it can be intimidating if you don’t have a basic understanding in place.

How to Use Regular Expressions in MongoDB

The find() command allows us to query documents from MongoDB and we’ll be adding our regular expression in this command to query only specific documents in our database.

Let’s take a look at a basic example so we can examine the basic usage before we delve into greater detail and examples. Remember to select the database with the use <database> command.

Example 1: Query for documents in the products collection within the current database with the name “Cola”.

db.products.find({"name" : /Cola/ })

As you can see we use the find() command as usual to query the name. This time though we require the name field to match our regular expression. We don’t need to give any other indication that it’s a regular expression search other than using the regular expression syntax in the query.

Syntax

Here, the regular expression begins and ends with a forward slash. There can though be option flags added to the expression. For example if you wanted the “Cola” search to be case-insensitive you can add the i flag to the expression like this:

db.products.find({"name" : /Cola/i })

This would match both Cola and cola.

A Short Regex Reminder

Just as a brief reminder let’s look at some of the matching basics in Regex:

  • . Matches any character except newlines
  • a Matches the character a
  • abc Matches the string of characters abc
  • a|b This is the OR operator. It would match a or b
  • a* This would match 0 or more a‘s
  • Use the backslash \ to escape special characters
  • d Matches a single digit
  • D Matches a single non-digit
  • s Matches a single whitespace
  • S Matches a single non-whitespace

Let’s also take a look at some of the flags you can use in your Regex:

  • i The case insensitive flag
  • m ^ and $ match start and end of line
  • s Allow . to match newline as well
  • x Allow spaces and comments

Here are two assertions we find very common:

  • ^ Pattern must match at start of string
  • $ Pattern must match at end of string

Another way to write Regex in MongoDB

There is a second way to write these queries which we will show side by side so you can see the difference:

db.products.find({"name" : /Cola/i })

This query from earlier can also be written as:

db.products.find({"name" : { $regex:"Cola", $options:"$i" }})

So if the syntax with the forward slashes is confusing to you, or you can’t remember whether it should be forward slashes or backslashes, we find this syntax more explicit.

Example

Let’s match text with the pattern “File01”, “File02”, “File99”. We are searching for the word “File” followed by two integers. The \d is the regular expression syntax to match any numeric digit.

db.products.find({"name" : /File_\d\d/ })

Or with the alternative syntax:

db.products.find({"name" : { $regex:"File_\d\d" })

Resources

If you’re trying to match a commonly used pattern like an email or domain name, we recommend researching it before trying to write it yourself because these are commonly tread patterns and you can save time by find an existing regular expression for it.

We also recommend using and online regular expression tester to test your regular expressions to make sure they are correct before you use them on your database. You don’t want to be sure that you’re regular expression is capturing the terms you think it its before you use it make any changes on your database.

Conclusion

In this article we showed you how to query MongoDB documents using the find() method with a regular expression. and gave you a few examples of regular expression syntax. Although this is the tip of the iceberg concerning regular expressions we hope this gets you on your way to creating the query you need. If you need any help managing your MongoDB instance please don’t hesitate to reach out to us at Object Rocket.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.