How to change a mongodb type from Double or Integer to String?

Convert Int to str:

db.dbname.find({fieldname: {$exists: true}}).forEach(function(obj) {
obj.fieldname= "" + obj.fieldname;
db.dbname.save(obj); });

I tried using this query. It was working for me. I think it is support till mongodb 3.4. In latest one might be now work.


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

Tags:

Mongodb