sql - How to query MongoDB with "like"

ID : 607

viewed : 172

Tags : sqlmongodbmongodb-querysql-likesql

Top 5 Answer for sql - How to query MongoDB with "like"

vote vote

97

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 regular expressions' '.*'), 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 information on regular expressions, refer to Regular expressions (MDN).

vote vote

86

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

Therefore:

For:

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

Output: paulo, patric

For:

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

Output: paulo, patric

For:

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

Output: pedro

vote vote

77

In

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

you can do:

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

61

In PHP, you could use the following code:

$collection->find(array('name'=> array('$regex' => 'm')); 
vote vote

52

Here are different types of requirements and solutions for string search with regular expressions.

You can do with a regular expression which contains a word, i.e., like. Also you can use $options => i for a case insensitive search.

Contains string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}}) 

Doesn't contain string, only with a regular expression

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}}) 

Exact case insensitive string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}}) 

Start with string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}}) 

End with string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}}) 

Keep Regular Expressions Cheat Sheet as a bookmark, and a reference for any other alterations you may need.

Top 3 video Explaining sql - How to query MongoDB with "like"

Related QUESTION?