How to convert NumberDecimal to Double in MongoDB shell?

心不动则不痛 提交于 2020-02-25 08:22:29

问题


I have a document with "test" filed as NumberDecimal type

{ "_id" : ObjectId("5d1a202e476381c30cd995a4"),  "test" : NumberDecimal("0.1") }

How to convert "test" field from NumberDecimal to Double in mongodb shell?

I tried execute

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

but don't solve this problem because it return NaN


回答1:


The decimal type is not native to JavaScript, so NumberDecimal values in the shell are special wrappers representing the BSON value stored in MongoDB. If you want to use parseFloat() you can convert a NumberDecimal to JSON in order to access the string value. For example, in your original code this would be: parseFloat(x.test.toJSON()["$numberDecimal"]) .

However, a better approach would be to use the aggregation framework to manipulate decimal values including arithmetic operations (MongoDB 3.4+) and type conversion (MongoDB 4.0+).

MongoDB 4.0+ includes a $toDouble() expression that will convert numeric values (decimal, int, long, boolean, date, string) to a double. The aggregation framework in MongoDB 4.0 cannot be used to update documents (unless you want to create a new collection or replace the existing collection using $out), so you would have to run an aggregation query to convert the values and then separately apply document updates:

// 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 (currently in RC) adds support for using some aggregation stages for updates, so in 4.2 the above update can be more concisely expressed as:

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


来源:https://stackoverflow.com/questions/56880268/how-to-convert-numberdecimal-to-double-in-mongodb-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!