12

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();
});
Alex Ryan
  • 3,719
  • 5
  • 25
  • 41
  • 1
    This question has been asked before. Take a look at the answer for this [`question`](http://stackoverflow.com/questions/4973095/mongodb-how-to-change-the-type-of-a-field) – Anand Jayabalan Sep 21 '14 at 00:25
  • Thanks. I had already read through these answers to that question and several others. Strangely, the top 2 answers for the question you mentioned don't seem to actually work. As indicated, the top answer converted the type to Object (type=3) instead of a String (type=2). The second most popular answer, made no change at all. – Alex Ryan Sep 21 '14 at 04:32

2 Answers2

20

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
yaoxing
  • 4,003
  • 2
  • 21
  • 30
1

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.

JayminLimbachiya
  • 971
  • 1
  • 13
  • 19