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'}})

2 Answers 2

2

Regex expression string needs to be escaped

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

MongoPlayground

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

could you help me with query .?
Wait: are you querying for the _id field or the courseId field? Your queries do not use the same field for querying. Was that a mistake in your question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.