How to query MongoDB with "like"
If you want to find documents in MongoDB with fields resembling a particular pattern, go ahead and use regex. Here's an example where you search for any 'name' field containing 'm' and disregard case:
The /i
ensures case-insensitivity, threading a path similar to SQL's LIKE
operator.
Digging deep – advanced pattern matching
Beyond basic pattern matching, MongoDB's regex opens up opportunities surpassing SQL's 'LIKE'. Here's how to drill down into the depths of its capabilities:
Using wildcards for exact matching
Let's say you need 'm' but you don’t care where it's coming from or going to:
The wildcard .*
is SQL's %
in disguise.
Starting and ending your searches right
Use ^
if you only want names starting with 'm':
And appoint $
for names ending with 'm':
All about the case – sensitive or not?
MongoDB allows you to toggle between case-sensitive and case-insensitive searches:
Avoiding the unwanted with negative lookahead
Distinctly avoid certain patterns using negative lookahead regex:
This will fetch names that don’t harbor the word 'unwanted'.
Regular expressions cheat sheets
Don't forget your Regex Cheat Sheets when defining complex patterns. And a detour to MDN Web Docs can always debunk your regex conundrums.
Plug and play regex across multiple languages
MongoDB regex can sneak in fluently in different programming languages with subtle syntax changes:
Python says "Hello, World!" to regex:
Node.js joins the regex party:
Tips and potential pitfalls
There're a few tricks and traps to watch out for when bending regex to your MongoDB whims:
Performance tweaks
Regular expressions may impact performance, especially if wildcards lead the way. Make your regex commands lean and fast by optimizing with indexes.
Escaping the special
If your patterns carry special characters, don't forget to escape them to ignore their special traits:
Test before you wreck
It's a regex rule of thumb to test your patterns for accuracy and efficiency before freewheeling them in production.
Was this article helpful?