Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 869
StackOverflowed Avatar asked Oct 22 '12 05:10

StackOverflowed


2 Answers

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);
});
like image 172
JohnnyHK Avatar answered Oct 02 '22 17:10

JohnnyHK


Based on the previous example by @JohnnyHK, I added regex also to the find query:

/*
MongoDB: Find by regular expression and run regex replace on results
*/
db.test.find({"url": { $regex: 'http:\/\/' }}).forEach(function(doc) {
  doc.url = doc.url.replace(/http:\/\/www\.url\.com/g, 'http://another.url.com'); 
  db.test.save(doc);
});
like image 33
zstolar Avatar answered Oct 02 '22 17:10

zstolar