Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mongodb
regex

How to query MongoDB with "like"

Abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

like operator

MongoDB doesn’t support the like operator which is common in SQL.

We can achieve the same functionality of the like operator using the find() function and regexes.

Syntax

db.users.insert({name: 'john'})
db.users.insert({name: 'johnny'})
db.users.insert({name: 'sam'})

Usecase 1: Contains a string

The SQL statement with the like operator is as follows:

select * from table where name like '%jo%';

In MongoDB,

db.users.find({name: /jo/})

Usecase 2: Starting with a string

The SQL statement with the like operator is as follows:

select * from table where name like 'jo%';

In MongoDB,

db.users.find({name: /^jo/})

Usecase 3: Ending with a string

The SQL statement with the like operator is as follows:

select * from table where name like '%jo';

In MongoDB,

db.users.find({name: /jo$/})

Let’s try the above commands in the terminal below.

Terminal 1
Terminal

RELATED TAGS

mongodb
regex

CONTRIBUTOR

Abhilash
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring