Explain Codes LogoExplain Codes Logo

How to query MongoDB with "like"

javascript
regex
mongodb
pattern-matching
Nikita BarsukovbyNikita Barsukov·Sep 28, 2024
TLDR

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:

db.users.find({"name": /m/i}) // Guess you are trying to find all entities 'm'ingling together! :)

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:

db.users.find({"name": /.*m.*/}) // 'm' is a free spirit, could be anywhere in the name!

The wildcard .* is SQL's % in disguise.

Starting and ending your searches right

Use ^ if you only want names starting with 'm':

db.users.find({"name": /^m/}) // 'm' has to be at the front of the line!

And appoint $ for names ending with 'm':

db.users.find({"name": /m$/}) // 'm' like to hang at the end. Cool 'm', isn't it?

All about the case – sensitive or not?

MongoDB allows you to toggle between case-sensitive and case-insensitive searches:

// Case-sensitive (exact John, not john or JOhN, because case matters!) db.users.find({ "name": { $regex: 'John' } }) // Case-insensitive (John, john, JOhN... all alike!) db.users.find({ "name": { $regex: 'John', $options: 'i' } })

Avoiding the unwanted with negative lookahead

Distinctly avoid certain patterns using negative lookahead regex:

db.users.find({"name": /^(?!.*unwanted).*/}) // 'unwanted' is not on the guest list, don't let them in!

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:

collection.find({"name": {"$regex": "world", "$options": "i"}}) # Python saying "Hello" to every world, big or small

Node.js joins the regex party:

collection.find({"name": new RegExp('world', 'i')}) // Node.js joins the regex party with the world

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:

db.users.find({ "name": /Jo\.Doe/ }) // The dot between Jo and Doe is just a dot, not a wildcard!

Test before you wreck

It's a regex rule of thumb to test your patterns for accuracy and efficiency before freewheeling them in production.