Pattern Matching in MongoDB

Pattern matching in MongoDB is commonly used to search for specific text within documents. MongoDB provides different ways to perform pattern matching using regular expressions (RegEx) and the $regex operator.


1. Using $regex for Pattern Matching

The $regex operator allows searching for patterns in string fields.

Example: Find Names Starting with 'A'

db.students.find({ "name": { "$regex": "^A" } })

Explanation:

  • ^A → Matches names that start with 'A'.

Example: Find Names Ending with 'e'

db.students.find({ "name": { "$regex": "e$" } })

Explanation:

  • e$ → Matches names that end with 'e'.

Example: Find Names Containing 'on'

db.students.find({ "name": { "$regex": "on" } })

Explanation:

  • on → Matches names that contain 'on'.

2. Case-Insensitive Matching

By default, MongoDB’s $regex is case-sensitive. To perform a case-insensitive search, use the i option.

Example: Find Names Containing 'john' (Case-Insensitive)

db.students.find({ "name": { "$regex": "john", "$options": "i" } })

Explanation:

  • $options: "i" → Makes the search case-insensitive.

3. Matching Multiple Patterns

To match multiple patterns, use the | (OR) operator inside the $regex.

Example: Find Names Containing 'Alice' or 'Bob'

db.students.find({ "name": { "$regex": "Alice|Bob" } })

Explanation:

  • Alice|Bob → Matches documents containing either 'Alice' or 'Bob'.

4. Pattern Matching in Aggregation

MongoDB also allows pattern matching in the aggregation pipeline using $match and $regex.

Example: Filter Students Whose Names Start with 'A'

db.students.aggregate([
  { "$match": { "name": { "$regex": "^A" } } }
]);

Explanation:

  • Uses $match in the aggregation pipeline to filter documents.

Conclusion

Pattern matching in MongoDB is powerful for searching text-based data. The $regex operator helps perform flexible searches, whether it’s case-insensitive, matching multiple values, or filtering in aggregation.