MongoDB - strip non numeric characters in field

StackOverflowed picture StackOverflowed · Oct 22, 2012 · Viewed 8.3k times · Source

I have a field of phone numbers where a random variety of separators have been used, such as:

932-555-1515
951.555.1255
(952) 555-1414

I would like to go through each field that already exists and remove the non numeric characters.

Is that possible?

Whether or not it gets stored as an integer or as a string of numbers, I don't care either way. It will only be used for display purposes.

Answer

JohnnyHK picture JohnnyHK · Oct 22, 2012

You'll have to iterate over all your docs in code and use a regex replace to clean up the strings.

Here's how you'd do it in the mongo shell for a test collection with a phone field that needs to be cleaned up.

db.test.find().forEach(function(doc) {
  doc.phone = doc.phone.replace(/[^0-9]/g, ''); 
  db.test.save(doc);
});