Im trying to do a query in mongodb similar to SQL example:
SELECT * from example where contactphone like '4832%';
My first idea was to do something like:
db.example.find({ contactphone: /^4832/ })
but it doesnt return what I am looking for, as contactphone is a number.
Is there any good practices-way to do such operations in mongodb on numbers?
EDIT: phone number may be a bad example. Lets say i need to find all numbers that CONTAIN number digit 9. How can i achive that?
Do not store telephone numbers as integers. Store them as strings. When you have a value which consists only of digits and on which arithmetics are pointless, like a zip-code, a bank account number or a telephone number, then storing it as a number does not make much sense.
All of this applies to almost any database, by the way, not just MongoDB.
But should you be absolutely determined to keep them as numbers, here are two things you can do.
$gt and $lt operators to search for a range. contactphone:{$gt:5556000, $lt:5556999} would find all numbers with the pattern 5556xxx.$where-query which uses a javascript function to internally convert every number to a string and then applies your regular expression to that string. $where: "String(this.contactphone).match(/^4832/) != null". I hope you don't have many documents in your database, because when you do, this query could take a while.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With