I want to query something with SQL\'s like
query:
SELECT * FROM users WHERE name LIKE \'%m%\'
How to do I achieve the same in
Regex are expensive are process.
Another way is to create an index of text and then search it using $search
.
Create a text Index of fields you want to make searchable:
db.collection.createIndex({name: 'text', otherField: 'text'});
Search for a string in text index:
db.collection.find({
'$text'=>{'$search': "The string"}
})
In SQL, the ‘like’ query is looks like this :
select * from users where name like '%m%'
In MongoDB console, it looks like this :
db.users.find({"name": /m/}) // Not JSON formatted
db.users.find({"name": /m/}).pretty() // JSON formatted
In addion pretty()
method will in all the places where produce formatted JSON structure which is more readable.
Already u got the answers but to match regex with case insensitivity
You could use the following query
db.users.find ({ "name" : /m/i } ).pretty()
The i
in the /m/i
indicates case insensitivity and .pretty()
provides a more pretty output
String deepakparmar, dipak, parmar
db.getCollection('yourdb').find({"name":/^dee/})
ans deepakparmar
db.getCollection('yourdb').find({"name":/d/})
ans deepakparmar, dipak
db.getCollection('yourdb').find({"name":/mar$/})
ans deepakparmar, parmar
There are already many answers. I am giving different types of requirements and solutions for string search with regex.
You can do with regex which contain word i.e like. Also you can use $options => i
for case insensitive search
Contains string
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
Doesn't Contains string
only with regex
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 this as a bookmark, and a reference for any other alterations you may need.
Use aggregation substring search (with index!!!):
db.collection.aggregate([{
$project : {
fieldExists : {
$indexOfBytes : ['$field', 'string']
}
}
}, {
$match : {
fieldExists : {
$gt : -1
}
}
}, {
$limit : 5
}
]);