01 May, 2020

MongoDB

liton

272 views


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.

note: mongodb uses regular expressions which are more powerful than "LIKE" in sql. With regular expressions you can create any pattern that you imagine.

For more info on regular expressions refer to this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

 

db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})

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

out: paulo, patric

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

out: paulo, patric

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

out: pedro

 

 

In

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

you can do:

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