Searching array elements with regex in Mongodb collection

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.

  1. searchableName – for example “Hair Style”
  2. 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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.

Leave a Reply