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:

    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

Your email address will not be published.