jsonmongodbmongoosejongo

Getting "Regular expression is invalid: missing )" error using json in MongoDb


I am running the query given below.

db.CollectionName.find({'serviceName':{'$regex':'^(ALBUMIN$','$options':'si'}})

I am getting the following error.

Error: error: {
    "ok" : 0,
    "errmsg" : "Regular expression is invalid: missing )",
    "code" : 2,
    "codeName" : "BadValue"
}

How can I avoid this error since bracket can be anywhere inside the string? Like- (ALBUMIN or ((ALBUMIN) etc.


Solution

  • You need to escape the ( character. You can use \ for escaping special characters in a regex. So for your case it would be like

    db.CollectionName.find({'serviceName':{'$regex':'^\\(ALBUMIN$','$options':'si'}})
    

    You can always test your regular expressions on https://regex101.com/ whenever you use it.