Text search in MongoDB with Regular Expression

For text search in MongoDB with Regular Expression, use $regex operator to match patterns within string fields. This allows you to search for documents containing specific text patterns or substrings.

Syntax

db.collection.find({
    "fieldName": { $regex: /pattern/ }
});

// Alternative syntax
db.collection.find({
    "fieldName": { $regex: "pattern", $options: "i" }
});

Sample Data

db.demo519.insertMany([
    {"Value": "50,60,70"},
    {"Value": "80,90,50"},
    {"Value": "10,30,40"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e88b9c0b3fbf26334ef6111"),
        ObjectId("5e88b9c7b3fbf26334ef6112"),
        ObjectId("5e88b9cfb3fbf26334ef6113")
    ]
}

View Sample Data

db.demo519.find();
{ "_id": ObjectId("5e88b9c0b3fbf26334ef6111"), "Value": "50,60,70" }
{ "_id": ObjectId("5e88b9c7b3fbf26334ef6112"), "Value": "80,90,50" }
{ "_id": ObjectId("5e88b9cfb3fbf26334ef6113"), "Value": "10,30,40" }

Example 1: Basic Regex Search

Find documents containing "50" in the Value field ?

db.demo519.find({ Value: { $regex: /50/ } });
{ "_id": ObjectId("5e88b9c0b3fbf26334ef6111"), "Value": "50,60,70" }
{ "_id": ObjectId("5e88b9c7b3fbf26334ef6112"), "Value": "80,90,50" }

Example 2: Case-Insensitive Search

db.demo519.find({ 
    Value: { $regex: "50", $options: "i" }
});

Example 3: Pattern Matching

Find documents where Value starts with "8" ?

db.demo519.find({ Value: { $regex: /^8/ } });
{ "_id": ObjectId("5e88b9c7b3fbf26334ef6112"), "Value": "80,90,50" }

Key Points

  • $regex supports JavaScript regular expression syntax
  • Use $options: "i" for case-insensitive matching
  • Patterns like ^ (start), $ (end), and .* (any character) work as expected

Conclusion

The $regex operator provides powerful pattern matching capabilities for text search in MongoDB. It supports both JavaScript regex syntax and string patterns with optional flags for flexible text searches.

Updated on: 2026-03-15T03:22:10+05:30

283 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements