DlutAF DlutAF - 1 year ago 104
Bash Question

mongo:how to query by regex in mongo

I am meeting a problem,just as follows:


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




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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download