This is my mongodb find query:
db.getCollection('candidate').find({
"$or": [
{
"email_id": {
"$regex": {
"regex": "^ranjit",
"flags": "i"
}
}
},
{
"mobile_no": {
"$regex": {
"regex": "^ranjit",
"flags": "i"
}
}
},
{
"phone_no": {
"$regex": {
"regex": "^ranjit",
"flags": "i"
}
}
},
{
"skill_name": {
"$regex": {
"regex": "^ranjit",
"flags": "i"
}
}
},
{
"current_address": {
"$regex": {
"regex": "^ranjit",
"flags": "i"
}
}
},
{
"first_name": {
"$regex": {
"regex": "^ranjit",
"flags": "i"
}
}
}
]
}
)
Above mongo db query return me wrong tuples. It returns tuples who doesn't contain "ranjit", but actually I want tuples who contain "ranjit".
Could you explain why it's returning wrong tuples and what is the correct query?
Your can try this
//like '%ranjit%'
db.getCollection('candidate').find($OR:[...{""email_id": /ranjit/},....])
//like 'ranjit%'
db.getCollection('candidate').find($OR:[...{""email_id": /^ranjit/},....])
//like '%ranjit'
db.getCollection('candidate').find($OR:[...{""email_id": /ranjit$/},....])
Using regex :
db.getCollection('candidate').find($OR[... {"email_id" : {$regex : ".*ranjit.*"}},...]);
If you need to search multiple fields for same query, you can add a new field in the document, which contains concatenated values of all the fields and then make regex search on that field. So the document with fields 'name', 'email', 'skillName' would change to:
{
name: 'Ranjit',
email: 'ranjit@someDomain.com',
skillName: 'MongoDB Administration',
gist: 'Ranjit|ranjit@someDomain.com|MongoDB Administration'
}
You can easily make a regex based search on field gist
. If you execute query on multiple fields, then a compound index will required to speed up the search, however in this case only one index will be required(for gist
).
Here is the query that you would be required to fire for the search operation:
db.getCollection('candidate').find({"gist": /ranjit/})