0

Below is my query which return result from database. I am using 3.2.22 mongo version

db.courses.find({_id:"edX-NYIF+CR.5x"});

Now I want fetch record of course Id which will be in lower case so I used below query it seems working fine if i use alpha character but not getting result for following course Id.

db.getCollection('courses').find({"_Id": { $regex : "edX-NYIF+CR.5x$" , $options: 'i'}})
Tejal
  • 764
  • 1
  • 10
  • 39

2 Answers2

2

Regex expression string needs to be escaped

db.getCollection('courses').find({"courseId": { $regex : "edX\\-NYIF\\+CR\\.5x$" , $options: 'i'}})

MongoPlayground

Anton
  • 3,587
  • 2
  • 12
  • 27
0

At first sight, your query looks OK... but I don't think this is going to work as you expected, because of the format of your ID.

The string "edX-NYIF+CR.5x" contains characters that have specific meanings for regexes, such as . and +, and perhaps some other IDs contain others. You should escape these first.

Looking at another SO question, there's a simple way to escape regex-sensitive characters:

string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

So escape your ID string and then use it in your query.

Here's a handy reference for special characters inside regular expressions, should you need it.

SolarBear
  • 4,534
  • 4
  • 37
  • 53