Build (escape) regexp in MongoDB?

To build and escape regular expressions in MongoDB, use the regex literal syntax with the /pattern/flags format or the $regex operator. The i flag enables case-insensitive matching, allowing you to find documents regardless of text case.

Syntax

// Method 1: Regex literal
db.collection.find({ field: /pattern/flags });

// Method 2: $regex operator
db.collection.find({ field: { $regex: "pattern", $options: "flags" } });

Sample Data

db.demo696.insertMany([
    { Message: "/Good/" },
    { Message: "(good)" },
    { Message: "/Bye/" },
    { Message: "(GOOD)" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea6d664551299a9f98c9391"),
        ObjectId("5ea6d67a551299a9f98c9392"),
        ObjectId("5ea6d68b551299a9f98c9393"),
        ObjectId("5ea6d693551299a9f98c9394")
    ]
}

Display Sample Data

db.demo696.find();
{ "_id": ObjectId("5ea6d664551299a9f98c9391"), "Message": "/Good/" }
{ "_id": ObjectId("5ea6d67a551299a9f98c9392"), "Message": "(good)" }
{ "_id": ObjectId("5ea6d68b551299a9f98c9393"), "Message": "/Bye/" }
{ "_id": ObjectId("5ea6d693551299a9f98c9394"), "Message": "(GOOD)" }

Example: Case-Insensitive Search

Find all documents containing "good" regardless of case using the i flag ?

db.demo696.find({ Message: /good/i });
{ "_id": ObjectId("5ea6d664551299a9f98c9391"), "Message": "/Good/" }
{ "_id": ObjectId("5ea6d67a551299a9f98c9392"), "Message": "(good)" }
{ "_id": ObjectId("5ea6d693551299a9f98c9394"), "Message": "(GOOD)" }

Key Points

  • The i flag makes regex searches case-insensitive
  • Regex patterns match substrings within field values
  • Special characters in data (like / and ()) don't interfere with regex matching

Conclusion

MongoDB regex with the /pattern/i syntax provides powerful text searching capabilities. The case-insensitive flag ensures flexible matching across different text variations in your documents.

Updated on: 2026-03-15T03:38:52+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements