MongoDB-去除字段中的非数字字符 [英] MongoDB - strip non numeric characters in field

查看:389
本文介绍了MongoDB-去除字段中的非数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电话号码字段,其中使用了各种各样的分隔符,例如:

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.

有可能吗?

无论它是否存储为整数或数字字符串,我都不在乎.它将仅用于显示目的.

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.

推荐答案

您将不得不遍历代码中的所有文档,并使用正则表达式替换来清理字符串.

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

这是在mongo shell中为需要清除的具有phone字段的test集合执行的操作.

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

这篇关于MongoDB-去除字段中的非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆