...

/

Querying with Regular Expressions

Querying with Regular Expressions

Learn to use regular expressions (regex) in MongoDB to define flexible search patterns, match specific text, and perform complex queries using metacharacters and flags.

What are regular expressions?

Regular expressions, also known as regex, are special text strings that define a search pattern. They can be used to search, match, and manipulate text within documents. MongoDB supports JavaScript-style regular expressions, making them both familiar and highly versatile.

Syntax:

Press + to interact
db.collection.find({ field: /pattern/ })

Here, field is the name of the field we want to search, and /pattern/ is the regex pattern we want to match. The pattern is enclosed between / slashes.

Components of a regular expression

Regex are not just random characters—they are a precise language for defining search patterns in text. At their core, regular expressions are made up of three main components:

  1. Literal characters

  2. Metacharacters

  3. Flags

Let's take a look at them in detail below: ...