0

How to match the given input value in MongoDB using regex, Since the value that was passed is greater than the value in the DB. Any suggestion? thanks.

Value in DB - 123456 Input Search Value - 1234560000

I have tried given below query ,but its not returning any result.

db.getCollection('STUDENT').find(
        {   Studentid:{$regex : '1234560000'}});   

FYI-> Studentid is String field.

Vasanth
  • 474
  • 2
  • 9
  • 31
  • https://stackoverflow.com/questions/20175122/how-can-i-use-not-like-operator-in-mongodb tried this reference as well . but no luck. – Vasanth Dec 04 '17 at 15:35

1 Answers1

1

From what it sounds like, you will have to know that the inputValue can be more characters (since we are talking strings) than your documents' IDs.

If you know that your input could be the ID you want followed by 'n' number of zero's (based on your example) then your regex would look more like:

inputValue = inputValue.replace("0", "");
db.getCollection('STUDENT').find( { Studentid:{$regex : inputValue + '[0]*'}});

My real suggestion is to use a number for the ID (be it int or long, that way you can do db.getCollection('STUDENT').find(eq("Sudentid", <inputValue>));

or if you're looking for multiple students

db.getCollection('STUDENT').find(gte("Sudentid", <inputValue>));

which returns all documents with Studentid greater than or equal to the inputValue.

Disclaimer: I'm not sure which version of the Mongo-driver you're using, but here are the docs I used and what my answer is based on: Mongo Driver Docs

0100Conan0111
  • 53
  • 1
  • 7
  • This scenario is working fine most of the cases except few like 2 student Ids 123450, 1234500 in DB, I am getting input value as 1234500000, I this case both the student Id is getting fetched. – Vasanth Dec 14 '17 at 12:49
  • If the zeros are the only thing different, then you should double check your regex. Here is a good place to try: https://regexr.com/ – 0100Conan0111 Dec 14 '17 at 18:44