MongoDB更改字段类型
需求背景
存储的数据为 Double 统计时造成精度丢失,需要改成 Decimal128
// 修改数据类型
db.getCollection('courseUserProgress').find({
courseLength: {
$type: 1
},
maxStudyLength: {
$type: 1
},
maxProgress: {
$type: 1
},
totalDuration: {
$type: 1
},
creditHour: {
$type: 1
}
}).forEach(function(doc) {
db.getCollection('courseUserProgress').updateOne({
_id: doc._id
}, {
$set: {
courseLength: new NumberDecimal(doc.courseLength),
maxStudyLength: new NumberDecimal(doc.maxStudyLength),
maxProgress: new NumberDecimal(doc.maxProgress),
totalDuration: new NumberDecimal(doc.totalDuration),
creditHour: new NumberDecimal(doc.creditHour)
}
})
})
字段类型$type的对应表如下:
mongo Shell中的数据类型如下:
可以根据自己需要更改的类型进行对应的修改