How to find Data with Special Character in MongoDB

Viewed 179

I need to find the data and data containing any of the special characters in the example I have used ( and ) bracket but it could be any. also, I need to exact in an incase-sensitive match with data. sample data:

[
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName (Special Box)",
   }
]

Expected Output:

[
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName (Special Box)",
   }
]

While I am using the query-

db.collection.aggregate([{
$match:{
"categoryName":{$regex:"categoryName (Special Box)"}
}
}])

I got the No data found in the response How to do this?

1 Answers

You just need to escape special characters, like so:

db.collection.aggregate([
    {
        $match: {
            "categoryName": {
                $regex: "categoryName \(Special Box\)"
            }
        }
    }
])
Related