Mongodb works Javascript way. Every mongodb collection is a JSON object containing all kinds of Javascript objects such as boolean, arrays, objects and strings.
In this example I am saving two different fields to my categories collection.
- searchableName – for example “Hair Style”
- keywords – curly, color, rebounding, etc.
I am creating a search field which is populated from this collection. So if I type “Hair” or curly, Color, Rebounding it should list my “Hair Style” category.
Here’s the query:
let findQuery = {
'$and': [{
'$or': [
{searchableName: new RegExp('^'+keyword)},
{
keywords: {
"$regex": new RegExp(keyword),
"$options": "i"
}
}
]
}]
};
let findQuery = {
'$and': [{
'$or': [
{searchableName: new RegExp('^'+keyword)},
{
keywords: {
"$regex": new RegExp(keyword),
"$options": "i"
}
}
]
}]
};
let findQuery = { '$and': [{ '$or': [ {searchableName: new RegExp('^'+keyword)}, { keywords: { "$regex": new RegExp(keyword), "$options": "i" } } ] }] };
Here $options with ‘i’ parameter specifies that we want to carry out search without considering upper or lower case.