Pages

Thursday, January 4, 2018

MongoDB Convert Field Type from String to Decimal in Bulk


Sometimes you want to convert a field type in MongoDB collection from one to another in bulk.

For example, you store the price of a product as type of string (maybe you are using MongoDB version older than 3.2 and you don't like using double). Now you have upgraded your MongoDB (3.4 or newer)  and you'd like to use the new data type "decimal128".

How can we do the type conversion for all the existing documents in the collection? It turned out to be quite simple. Here is the code snippet you can run through the mongo command line to do the conversion.


db.product.find({ 'price': { $type : 2}}) /* or $type: "string" */
  .forEach( function (x) { 
    x.price = new NumberDecimal(x.price); 
    db.product.save(x); 
  });

You will need to make sure the field contains the valid string that can be converted. If not, it is better to do some validation or cleanse by expanding the above code snippet.

Reference:
https://docs.mongodb.com/manual/reference/operator/query/type/

1 comment:

  1. How To Play Spades in Vegas - Mapyro
    This is a game that 포커 고수 is played with two people. The first person to go 상주 출장샵 into is the banker, the 안동 출장안마 second player to 익산 출장안마 play. There is no player with 거제 출장마사지 two

    ReplyDelete