MongoDB type update from NumberLong to String

I’ve imported CSV file to my mongodb. CSV have separators as needed to mongo and was received from MySQL database with this query:
SELECT * FROM csgo_users INTO OUTFILE 'b1.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY 'n';
Also I’ve tried to receive CSV from Sequel Pro with it’s export functions.
In my csv I have field with 17 characters length. In MySQL database this field has type VARCHAR but contains 17-digits number.
After importing csv to mongo I got this field with type NumberLong, but I want it to be string.
I’ve tried so far to:

  • Change type in MySQL from varchar to text.
  • Tried to import csv with additional flags --headerline and --columnsHaveTypes
  • Also I’ve tried to add separate fields without top line, with tag --fields.
  • Tried commands as this:

    db.csgo_users.find({"steam_id": {$type: 18}})
           .toArray()
           .map(function(v){
               v.steam_id = new String(v); 
               db.csgo_users.save(v)
            })
    

or this:

db.csgo_users.find({"steam_id": {$type: 18}})
  .toArray()
  .map(function(v){
     v.steam_id = new String(v.toSring());
     db.csgo_users.save(v)
  })


– I’ve tried a lot of solutions with forEach() like this or this or this etc.


For the last one example of my tries I’ve got not string, but Object, {"N",u","m","b","e","r","L","o","n","g"..} but I want it to be “123456789”, not Object.
I’m using MongoDB 3.4 docs.
So, my question is, how to change “field” type from NumberLong to String?

Answer

You can use valueOf() to get the value of a NumberLong as a javascript number value.

Casting NumberLong to Number :

NumberLong('5').valueOf() // 5

Then, you can then use easilly toString() on your number to get the String value.

Casting NumberLong to String :

NumberLong('5').valueOf().toString() // "5"

Leave a Reply

Your email address will not be published. Required fields are marked *