How To change data type in MongoDB

In this article, I will let you know how to change data type from String to Integer and vice versa.
String to Integer data type conversion
1. First check is there any data in string for which you want to convert the data to Integer 64, It’s NumberLong() data type in MongoDB.
db.collection_name.find({"field_name": {$exists: true, $type : 2}  } )
If count is more than 0 then it means data is in String for the specific field_name.
2. Conversion to Integer from String
db.collection_name.find({"field_name": {$exists: true, $type : 2}  }).forEach( function (x) { x.field_name = new NumberLong(x.field_name); db.collection_name.save(x); });
Above java script function will convert String type data to Integer 64.
3. If field has empty string then you can convert that docs to NumberLong(0) as per given below statement.
db.collection_name.find({"field_name": {$eq = "", $type : 2}  }).forEach( function (x) { x.field_name = new NumberLong(0); db.collection_name.save(x); });
Integer data type to String conversion
1. Check whether any docs are there or not from the given below query.
db.collection_name.find({"field_name": {$exists: true, $type : 18}  } )
If Count is more than 0 then follow the next steps.
2. Conversion of Integer data to String.
db.collection_name.find({"field_name": {$exists: true, $type : 18}  }).forEach( function (x) { x.field_name = "" + x.field_name; db.collection_name.save(x); });
Thanks for the going through the article

No comments:

Post a Comment