2012-03-30 19 views
1

我有3个字段的CSV:名称,纬度,经度。一排看起来像这样:从CSV中的独立经度和纬度列的蒙古进口位置

Place 1,73.992964,40.739037 

什么是mongoimport进入loc域的经纬度的正确方法是什么?我知道位置索引字段需要经度,纬度,而不是2个离散字段的纬度和经度,但我错过了,如果有办法处理从谨慎的价值观到数组通过mongoimport

我是否需要首先转换为带有经度和纬度的单列圆柱的CSV?

Place1,[-73.992964,40.739037] 

我经常将要处理与具有纬度和经度存储在独立的栏目,所以我希望能找到一种方法与mongoimport做到这一点的CSV。

回答

2

Mongoimport的功能非常有限,在这种情况下,官方的建议是编写一个自定义脚本,它可以逐行解析csv文件,并按照您希望它们表示的方式创建文档。

为了使地理空间索引被创建时,位置信息必须存储在相同的密钥下,如所描述的:部分在地理空间索引文档的顶部:http://www.mongodb.org/display/DOCS/Geospatial+Indexing

导入“一些例子”直接从.csv文件中的数据是这样生成的文件:

doc1.csv: 
place, lat, lon 
Place 1,73.992964,40.739037 

$ ./mongoimport -d test -c a --type csv --headerline --file doc1.csv 

> db.a.find() 
{ "_id" : ObjectId("4f7602d70c873ff911798fd3"), "place" : "Place 1", "lat" : 73.992964, "lon" : 40.739037 } 

不幸的是,这是不可能创造上述文档上的地理空间索引。

通过实验,我试图导入一个.csv文件,其中包含您描述的第二种格式的数据,但没有成功。

doc2.csv: 
place, loc 
Place1,[-73.992964,40.739037] 

$ ./mongoimport -d test -c b --type csv --headerline --file doc2.csv 

> db.b.find() 
{ "_id" : ObjectId("4f7602e40c873ff911798fd4"), "place" : "Place1", "loc" : "[-73.992964", "field2" : "40.739037]" } 

作为进一步的实验,我将.csv文件改成了json格式,并导入了它,它似乎工作。

doc3.json: 
{name:"Place1" , loc:[-73.992964,40.739037]} 

$ ./mongoimport -d test -c c --type json --file doc3.json 

> db.c.find() 
{ "_id" : ObjectId("4f7604570c873ff911798fd5"), "name" : "Place1", "loc" : [ -73.992964, 40.739037 ] } 

但是,如果你正在编写一个脚本来所有的.csv文件转换成以.json格式,你可能会更好过编写自定义脚本导入直接您的.csv文件到您的收藏吧。

+0

非常感谢这么详细的检查。预处理是我前进的方式,但我只是想确保我没有在mongoimport中丢失某些东西。 – Nick 2012-03-30 19:30:52

1

我经历了类似的问题,我解决它通过使用sed到CSV转换成合适的JSON格式进行短预处理通(也使用新GeoJSON objects):

sed 's/\([^,]*\),\([0-9.-]*\),\([0-9.-]*\)/{ place: \1, location:{ type: "Point", coordinates: [ \3, \2 ] } }/' <data.csv >data.json 

一个什么样的一种解释怎么回事:

sed   // Execute the sed command 
's/   // Use substitute mode 

\([^,]*\) // Match a string containing anything except a ',' [1] 
,   // Match a single ',' (the separator) 
\([0-9.-]*\) // Match any combination of numbers, '.' or '-' [2] 
,   // Match a single ',' (the separator) 
\([0-9.-]*\) // Match any combination of numbers, '.' or '-' [3] 

/{ place: \1, location:{ type: "Point", coordinates: [ \3, \2 ] } }/' 
// Replace the match with the appropriate JSON format, inserting 
// parts of the matched pattern ([1],[2],[3]) 

<data.csv // Perform the command on the contents of the data.csv file 
>data.json // Output the results to a data.json file 

我发现sed的是相当有效的,甚至含有〜800万行的CSV文件,只用了1分钟左右来进行这种转换。

然后,使用mongoimport导入新创建的JSON文件变得非常简单,如Marc的回答所示。