MongoDB - Regular Expression
MongoDB - Regular Expression (Regex) Queries
Section titled “MongoDB - Regular Expression (Regex) Queries”MongoDB supports regular expressions in queries for advanced string pattern matching. You can use the $regex operator or the shorthand /pattern/ syntax. MongoDB uses the PCRE (Perl Compatible Regular Expression) engine.
Unlike text search, you do not need to create a special index to use regex, but performance is a critical consideration. Let’s use a sample posts collection:
db.posts.insertOne({ "post_text": "enjoy the mongodb articles on w3", "tags": [ "mongodb", "w3" ]});
db.posts.insertOne({ "post_text": "hey! this is my post on TutorialsPoint", "tags": ["TutorialsPoint"]});Using the $regex Operator
Section titled “Using the $regex Operator”The following query finds all posts where post_text contains the substring “w3”.
// Using the $regex operatordb.posts.find({ post_text: { $regex: "w3" } });
// Shorthand syntax (often used in the shell for convenience)db.posts.find({ post_text: /w3/ });Case-Insensitive Matching
Section titled “Case-Insensitive Matching”To make a search case-insensitive, use the i option. This will match w3, TutorialsPoint, TUTORIALSPOINT, etc.
// Using the $options parameterdb.posts.find({ post_text: { $regex: "w3", $options: "i" } });
// Shorthand syntax with the 'i' flagdb.posts.find({ post_text: /w3/i });Using Regex on Array Elements
Section titled “Using Regex on Array Elements”You can apply regex to elements within an array. This is useful for searching through tags. The following query finds posts where any tag starts with the word “mongo”.
// The '^' character anchors the match to the beginning of the stringdb.posts.find({ tags: { $regex: "^mongo", $options: "i" } });Performance and Indexing for Regex Queries
Section titled “Performance and Indexing for Regex Queries”This is the most critical aspect of using regex in MongoDB. Performance can vary dramatically based on how you write your expression.
Best Practice: Anchored, Case-Sensitive Prefixes
Section titled “Best Practice: Anchored, Case-Sensitive Prefixes”If a regular B-tree index exists on a field, MongoDB can use it to optimize regex queries that are “prefix expressions”. This means the expression is anchored to the start of the string (^).
// First, create an index on the 'post_text' fielddb.posts.createIndex({ post_text: 1 });
// This query can use the index because it's a prefix expression.// It's fast because it only needs to scan the part of the index starting with 'enjoy'.db.posts.find({ post_text: { $regex: "^enjoy" } });Common Pitfall: Un-anchored or Case-Insensitive Regex
Section titled “Common Pitfall: Un-anchored or Case-Insensitive Regex”Regex queries that are not anchored to the beginning of the string, or that use the i option for case-insensitivity, cannot effectively use a standard B-tree index. These queries will result in a collection scan (COLLSCAN), which is very slow on large collections.
// WARNING: PERFORMANCE BOTTLENECK// This query will scan every document in the collection, ignoring the index.db.posts.find({ post_text: { $regex: "articles", $options: "i" } });Pro-Tip: When to Use Regex vs. Text Search
Section titled “Pro-Tip: When to Use Regex vs. Text Search”- Use Regex for precise, pattern-based matching where you need to find specific structural patterns (e.g., email formats, SKUs) or for index-optimized prefix searches.
- Use Text Search for natural language queries, searching for words or phrases in any position, ranking by relevance, and leveraging language-specific stemming. It is almost always the better choice for searching human-written text.