2014-09-20 62 views
8

我用mongoimport將一些csv數據導入到mongodb中。如何將MongoDB類型從Double或Integer更改爲String?

它主要是正確創建類型,但有一些情況下,在需要字符串的位置創建雙精度或整數。

我試過幾種技術將這些字段轉換爲字符串無濟於事。

這是我曾嘗試:

這產生不希望改變一個對象類型(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); 
}); 

結果是這樣的:

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

這產生沒有變化:

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

這產生沒有變化:

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

這產生沒有變化:

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

這產生沒有變化:

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

這產生一個錯誤:類型錯誤:對象0.22沒有方法'toNumber'

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

此問題已被提問。看看這個['問題']的答案(http://stackoverflow.com/questions/4973095/mongodb-how-to-change-the-type-of-a-field) – 2014-09-21 00:25:09

+0

謝謝。我已經閱讀了這個問題的答案和其他幾個。奇怪的是,你提到的問題的前2個答案似乎並沒有實際工作。如上所示,頂級答案將類型轉換爲Object(type = 3)而不是String(type = 2)。第二個最受歡迎的答案完全沒有改變。 – 2014-09-21 04:32:19

回答

11

如果要存儲轉換後的數據,則需要update該文檔,否則更改後的文檔將轉到不存在的地方。

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

至於toNumber問題,它不是內置函數。您可能需要使用parseIntparseFloat代替:

parseInt("1000"); // output: 1000 
相關問題