like
operatorMongoDB 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.
db.users.insert({name: 'john'})
db.users.insert({name: 'johnny'})
db.users.insert({name: 'sam'})
The SQL statement with the like
operator is as follows:
select * from table where name like '%jo%';
In MongoDB,
db.users.find({name: /jo/})
The SQL statement with the like
operator is as follows:
select * from table where name like 'jo%';
In MongoDB,
db.users.find({name: /^jo/})
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.
Free Resources