How to query MongoDB with “like”?

Technology CommunityCategory: MongoDBHow to query MongoDB with “like”?
VietMX Staff asked 3 years ago

I want to query something as SQL’s like query:

select * 
from users 
where name like '%m%'

How to do the same in MongoDB?

Answer

db.users.find({"name": /.*m.*/})
// or
db.users.find({"name": /m/})

You’re looking for something that contains “m” somewhere (SQL’s '%' operator is equivalent to Regexp’s '.*'), not something that has “m” anchored to the beginning of the string.