如何在MongoDB shell中将NumberDecimal转换为Double?

如何在MongoDB shell中将NumberDecimal转换为Double?,mongodb,mongodb-query,decimal,bigdecimal,mongo-shell,Mongodb,Mongodb Query,Decimal,Bigdecimal,Mongo Shell,我有一份“测试”文件,归档为NumberDecimaltype { "_id" : ObjectId("5d1a202e476381c30cd995a4"), "test" : NumberDecimal("0.1") } 如何在mongodb shell中将“test”字段从NumberDecimal转换为Double 我试着执行 db.collection.find({"test": {$exists: true}}).forEach(function (x) { x.test =

我有一份“测试”文件,归档为
NumberDecimal
type

{ "_id" : ObjectId("5d1a202e476381c30cd995a4"),  "test" : NumberDecimal("0.1") }
如何在mongodb shell中将“test”字段从
NumberDecimal
转换为
Double

我试着执行

db.collection.find({"test": {$exists: true}}).forEach(function (x) {   x.test = parseFloat(x.test);   db.collection.save(x); });

但是不要解决这个问题,因为它返回NaN

十进制类型不是JavaScript固有的,所以shell中的NumberDecimal值是表示存储在MongoDB中的BSON值的特殊包装。如果要使用
parseFloat()
可以将NumberDecimal转换为JSON以访问字符串值。例如,在原始代码中,这是:
parseFloat(x.test.toJSON()[“$numberDecimal]”)

但是,更好的方法是使用聚合框架操纵十进制值,包括算术运算(MongoDB 3.4+)和类型转换(MongoDB 4.0+)

MongoDB 4.0+包含一个将数值(十进制、整数、长、布尔、日期、字符串)转换为双精度的函数。MongoDB 4.0中的聚合框架无法用于更新文档(除非您希望使用创建新集合或替换现有集合),因此您必须运行聚合查询来转换值,然后分别应用文档更新:

//查找匹配的文档
var docs=db.collection.aggregate([
{$match:{
测试:{$exists:true}
}},
//添加一个新字段,将十进制转换为双精度
//(或者,也可以替换原始“测试”值)
{$addFields:{
testDouble:{$toDouble:$test}
}}
])
//使用更改进行更新(注意:这可能是为了提高效率而进行的批量更新)
docs.forEach(函数(doc){
update({{u id:doc.{u id},{$set:{testDouble:doc.testDouble}});
});
//检查结果
>db.collection.find().limit(1)
{
“_id”:ObjectId(“5d1a202e476381c30cd995a4”),
“测试”:数字CIMAL(“0.1”),
“testDouble”:0.1
}
MongoDB 4.2(目前在RC中)增加了对使用一些的支持,因此在4.2中,上述更新可以更简洁地表示为:

db.collection.updateMany(
    { test: { $exists: true }},
    [ { $addFields: { testDouble: { $toDouble: "$test" }}}]
)

@史丹妮:谢谢你的回答!我还通过字符串处理解决了这个问题,比如
db.collection.find({“test”:{$exists:true}}).forEach(函数(x){var s=x.test.toString().split('“'))[1];x.test=parseFloat(s);db.collection.save(x);});
,但我认为您的解决方案是最好的^^