regexmongodbmlab

MongoDB - strip non numeric characters in field


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.


Solution

  • 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);
    });