Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();
});
like image 377
Alex Ryan Avatar asked Sep 20 '14 23:09

Alex Ryan


2 Answers

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
like image 111
yaoxing Avatar answered Oct 20 '22 00:10

yaoxing


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.

like image 42
JayminLimbachiya Avatar answered Oct 19 '22 23:10

JayminLimbachiya