我有一个文档,其中的“NumberDecimal
”被归档为测试类型
{ "_id" : ObjectId("5d1a202e476381c30cd995a4"), "test" : NumberDecimal("0.1") }
如何在mongodb shell中将测试字段从NumberDecimal
转换为Double
?
我试着执行
db.collection.find({"test": {$exists: true}}).forEach(function (x) { x.test = parseFloat(x.test); db.collection.save(x); });
但是不要解决这个问题,因为它返回NaN
发布于 2019-07-05 10:38:00
decimal类型不是JavaScript的原生类型,因此shell中的BSON值是表示存储在MongoDB中的NumberDecimal值的特殊包装器。如果要使用parseFloat()
,可以将NumberDecimal转换为JSON以访问字符串值。例如,在您的原始代码中,这将是:parseFloat(x.test.toJSON()["$numberDecimal"])
。
但是,更好的方法是使用聚合框架来处理十进制值,包括算术运算(MongoDB 3.4+)和类型转换(MongoDB 4.0+)。
MongoDB 4.0+包含一个将数值(十进制、整型、长整型、布尔型、日期型、字符串)转换为双精度型的$toDouble()
expressionMongoDB 4.0中的聚合框架不能用于更新文档(除非您希望使用$out
创建新集合或替换现有集合),因此您必须运行聚合查询来转换值,然后单独应用文档更新:
// Find matching documents
var docs = db.collection.aggregate([
{ $match: {
test: { $exists: true }
}},
// Add a new field converting the decimal to a double
// (alternatively, the original "test" value could also be replaced)
{ $addFields: {
testDouble: { $toDouble: "$test" }
}}
])
// Update with the changes (Note: this could be a bulk update for efficiency)
docs.forEach(function (doc) {
db.collection.update({ _id: doc._id}, {$set: { testDouble: doc.testDouble }});
});
// Check the results
> db.collection.find().limit(1)
{
"_id" : ObjectId("5d1a202e476381c30cd995a4"),
"test" : NumberDecimal("0.1"),
"testDouble" : 0.1
}
MongoDB 4.2 (目前在RC中)增加了对使用一些aggregation stages for updates的支持,因此在4.2中,上面的更新可以更简洁地表达为:
db.collection.updateMany(
{ test: { $exists: true }},
[ { $addFields: { testDouble: { $toDouble: "$test" }}}]
)
https://stackoverflow.com/questions/56880268
复制相似问题