how do i query mongodb with like

Question!

I want query something as SQL's like query:

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

How to do the same in mongodb? I can't find a operator for like in the documentation.



Answers
That would have to be:

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

or, similar,

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.

By : Kyle H


out: paulo, patric

db.users.find({name: /^pa/}) //like 'pa%' 

out: paulo, patric

db.users.find({name: /ro$/}) //like '%ro'

out: pedro



In

  • Python, using PyMongo
  • Mongoose using Node.js
  • Java, using Jongo
  • Go, using mgo

you can do:

db.users.find({'name': {'$regex': 'sometext'}})


This video can help you solving your question :)
By: admin