2015-07-19 479 views
0

我使用了mongoimport导入csv文件。此数据集要具体:MongoDB:将字段类型从String转换为Array

https://www.google.com/fusiontables/DataSource?docid=1d7Qps--r0i-E4drYQQzntSdXN8xJ4-6qk24CiMed#map:id=3

我遇到的问题是与description领域。

[{"landing_point_id":3522,"latlon":"51.898325,-8.472768","name":"Cork, Ireland"}] 

我想,这是对象的数组,所以我作出了猫鼬模型是这样的:

description: [{ 
    landing_point_id: Number, 
    latlon: String, 
    name: String 
     }], 

但是这给了我一个空数组。如果我将description的类型设置为String,我确实得到了值 - 但当然是字符串,所以属性不可访问。

"description" : "[{\"landing_point_id\":8398,\"latlon\":\"52.207114,1.620294\",\"name\":\"Sizewell, United Kingdom\"}]" 

所以,问题似乎是,该领域descriptionString时,我想它是一个Array

以下的答案我试图将它从字符串转换为数组,但没有运气。

db.cables.find().snapshot().forEach(function (el) { 
    el.description_array = [ el.description ]; 
    db.cables.save(el); 
}); 

这只是将字符串包装在另一个数组中。

"description_array" : [ "[{\"landing_point_id\":8398,│ col10: '', 
\"latlon\":\"52.207114,1.620294\",\"name\":\"Sizewell, United Kingdom\"}]" ] 

与同为

el.description_array = new Array(el.description); 

任何想法如何解决这个问题?

有些东西可以在导入之前在csv文件中编辑,以使mongoimport正确解释它?

回答

0

现在需要将“字符串”“解析”为一个有效的数据结构。同样,“latlong”对你来说也是无用的,因为它既是一个“字符串”本身,也是对于MongoDB期望坐标的错误顺序。

所以我们解决这两个:

var bulk = db.cables.initializeOrderedBulkOp(), 
    count = 0; 

db.cables.find({ "description": { "$type": 2 } }).forEach(function(doc) { 
    doc.description = JSON.parse(doc.description); 
    doc.description = doc.description.map(function(desc) { 
     desc.coordinates = desc.latlon.split(",").reverse().map(function(el) { 
      return parseFloat(el); 
     }); 
     delete desc.latlong; 
     return desc; 
    }); 

    bulk.find({ "_id": doc._id }).updateOne({ 
     "$set": { "description": doc.description } 
    }); 
    count++; 

    // Send batch one in 1000 
    if (count % 1000 == 0) { 
     bulk.execute(); 
     bulk = db.cables.initializeOrderedBulkOp(); 
    } 
}); 

// Clear any queued 
if (count % 1000 != 0) 
    bulk.execute(); 

你的猫鼬的模式改成这样:

"description": [{ 
    "landing_point_id": Number, 
    "coordinates": [], 
    "name": String 
}], 

现在你有数据你可以索引和地理空间查询使用。

+0

非常感谢!并且还需要坐标的帮助(是我的修复列表中的下一件事)。 –

相关问题