Mongodb – How to change a mongodb type from Double or Integer to String

mongodb

I used mongoimport to import some csv data into mongodb.

It mostly created types correctly but there are a few instances where Doubles or Integers were created where Strings are desired.

I've tried several techniques to convert these fields to strings to no avail.

Here's what I have tried:

This produced an undesired change to an Object type (type=3):

db.temp.find( { 'name' : { $type : 16 } } ).forEach( function (x) { 
  x.name = new String(x.name); // convert field to string 
  db.temp.save(x); 
});

Result looked like this:

> db.temp.findOne({name: {$type:3}})
{
    "_id" : ObjectId("541a28ddbf8a2e3ee8439b58"),
    "name" : {
        "0" : "0",
        "1" : ".",
        "2" : "2",
        "3" : "2"
    }
}

This produced no change:

db.temp.find({name: {$exists:true}}).forEach( function(x) {
  x.name = "" + x.name;
});

This produced no change:

db.temp.find({name: {$exists:true}}).forEach( function(x) {
  x.name = x.name + "";
});

This produced no change:

db.temp.find({name: {$exists:true}}).forEach( function(x) {
  x.name = "" + x.name + "";
});

This produced no change:

db.temp.find({name: {$exists:true}}).forEach( function(x) {
  x.name = x.name.toString();
});

This produced an error: TypeError: Object 0.22 has no method 'toNumber'

db.temp.find({name: {$exists:true}}).forEach( function(x) {
  x.name = x.name.toNumber().toString();
});

Best Answer

If you want to store the converted data, you'll need to update the document, otherwise the changed document goes to no where.

db.temp.find({name: {$exists:true}}).forEach( function(x) {
    db.temp.update({_id: x._id}, {$set: {name: x.name.toString()}});
});

As to the toNumber issue, it's not an build-in function. You may want to use parseInt or parseFloat instead:

parseInt("1000");  // output: 1000