DlutAF
DlutAF

Reputation: 53

mongo:how to query by regex in mongo

I am meeting a problem,just as follows:

 {"_id":ObjectId("XXXXXXXX"),"phone":"123456"}

and now i want to query the document that the length of phone field is 5. I run the command as follows,

db.Phone.find({"phone":{"$regex":"\d{5}"}})

or

db.Phone.find({"phone":/\d{5}/})

they all do not Work. Could anybody help me figure out, how to use regex in mongo?

Upvotes: 0

Views: 2427

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

If you want to find docs where the phone number is exactly 5 digits, you need to anchor the regex to the start and end of the string with ^ and $:

db.Phone.find({phone: /^\d{5}$/})

Otherwise it will match any string that contains at least 5 digits in a row, anywhere in the string.

Upvotes: 4

Related Questions