MongoDB - Update data type of field

Viewed 3244

The data got inserted as below.

{"key1": 20.05, "key2": 21.24 }

It was expected to be stored as Double, but the value was stored as String and when the document was returned, the value was,

{"key1": "20.05", "key2": "21.24" }

Is there anyway to update the data type to double without scanning each document?

1 Answers

Note

By default, all numbers are stored as double in MongoDB unless generally cast overwise.

Reference: https://stackoverflow.com/a/31267615/10861398


MongoDB version 4.2 above

You can update the type data of the field with aggregation. Below is an example of an aggregate query to change the data type in the $key2 field to double.

db.collection.aggregate([
  {
    $set: {
      key2: { $toDouble: '$key2' },
    },
  },
])

if the data to be converted to double cannot be altered (ex: "4Bn"), an error will occur. To prevent this, you can use an additional operator called $convert.

Reference: $toDouble


MongoDB version 3.2 above

MongoDB does not yet support operator $set in aggregation in this version. So you have to do it manually with find, forEach, and updateOne.

Example using mongo shell:

db.collection.find({}).forEach(function (doc) {
  db.collection.updateOne(
    {
      _id: doc._id,
    },
    {
      $set: {
        key2: NumberInt(doc.key2),
      },
    }
  )
})

Reference: NumberInt

Related