1
mongodb 修改字段类型
发布于: 2021 年 05 月 23 日
在如下 collection 中 reading 字段本应该是 string 类型,但是在写入时错误的将其写成了 int,此时需要 int 类型改为 string 类型。
{    "_id" : ObjectId("5d79097debeae9d530225b93"),    "type" : 2,    "name" : "ZhiHu",    "intime" : NumberLong(1568213373),    "data" : [         {            "top" : "1",            "title" : "六种配色、5499 元起的 iPhone 11 系列发布,配置和性能如何?",            "reading" : 72920000,            "url" : "https://www.zhihu.com/question/345431917",            "state" : ""        },         {            "top" : "2",            "title" : "男生找对象看重什么?",            "reading" : 35880000,            "url" : "https://www.zhihu.com/question/292443025",            "state" : ""        }	]}复制代码
 解决方法:
在 MongoDB 的 shell 中执行如下语句即可:
db.zhihu.find({}).forEach(function(item){item.data.forEach(function(x){x.reading = String(x.reading); db.zhihu.save(item)})});复制代码
 执行修改后的reading变成了 string, 结构如下:
{    "_id" : ObjectId("5d79097debeae9d530225b93"),    "type" : 2,    "name" : "ZhiHu",    "intime" : NumberLong(1568213373),    "data" : [         {            "top" : "1",            "title" : "六种配色、5499 元起的 iPhone 11 系列发布,配置和性能如何?",            "reading" : "72920000",            "url" : "https://www.zhihu.com/question/345431917",            "state" : ""        },         {            "top" : "2",            "title" : "男生找对象看重什么?",            "reading" : "35880000",            "url" : "https://www.zhihu.com/question/292443025",            "state" : ""        }  ]}复制代码
 划线
评论
复制
发布于: 2021 年 05 月 23 日阅读数: 14
xiaolu
关注
还未添加个人签名 2018.09.17 加入
后端程序员,目前从事流媒体方向开发,工作C/C++,业余玩Python/Go。











    
评论