如何重新构建MongoDb集合

时间:2014-07-28 15:40:53

标签: mongodb

我需要使用以下结构查询MongoDb集合:

{
"_id" : ObjectId("53cfc8bf8f11381e28373153"),
"name" : "0700452",
"description" : "",
"styleurl" : "#style00001",
 "point" : {
    "altitudemode" : "clampToGround",
    "coordinates" : "11.8263919657018, 41.2129293739724, 1.02757364822173"
 }
}

我需要做的查询类型是基于2dsphere索引搜索,但是当我尝试这个时:

db.coordinatas.find({ $near : { type:'Point', point:{coordinates:"15.8263919657018, 41.2129293739724"}, $maxDistance : 100 }});

我收到错误:

error: {
    "$err" : "can't find any special indices: 2d (needs index), 2dsphere (needs index),  for: { $near: { type: \"Point\", point: { coordinates: \"15.8263919657018, 41.2129293739724\" }, $maxDistance: 100.0 } }",
    "code" : 13038
}

与错误所说的索引相反:

[
{
    "v" : 1,
    "key" : {
        "_id" : 1
    },
    "ns" : "test4-dev.coordinatas",
    "name" : "_id_"
},
{
    "v" : 1,
    "key" : {
        "coordinates" : "2dsphere"
    },
    "ns" : "test4-dev.coordinatas",
    "name" : "coordinates"
}

这可能是因为2dsphere索引需要一个两个坐标的数组 我想也许我可以用这种新格式重新构建集合:

{
"_id" : ObjectId("53cfc8bf8f11381e28373153"),
"name" : "0700452",
"coordinates": [11.8263919657018, 41.2129293739724]
}

以这种方式查询集合:

db.coordinatas.find({ $near : {type:'Point', coordinates:[11.8263919657018, 41.2129293739724], $maxDistance : 100 }});

如何更改新系列中旧系列的格式?

2 个答案:

答案 0 :(得分:1)

this page中所述:

  

[2dsphere]索引支持存储为GeoJSON对象和遗留坐标对的数据。该索引通过将数据转换为GeoJSON Point类型来支持传统坐标对。

如果您要转换数据,我建议您将其转换为GeoJSON point,如下所示:

{ loc: { type: "Point", coordinates: [ 11.8263919657018, 41.2129293739724 ] } } 

为此,您必须运行一个脚本,您可以在其中执行以下操作:

  1. 遍历所有文件。
  2. 为每个文档检索两个坐标值。
  3. 使用新坐标值,创建一个GeoJSON字段。
  4. 取消设置上一个字段。
  5. 转换完所有文档后,您可以删除旧索引并使用新字段名称构建新索引。

    <强>更新

    作为参考,这是一种通过mongo shell更新集合的方法。您可能会发现它很有用。

    // Iterate through all the documents and set the new field
    // with the GeoJSON point using the old coordinates string. 
    db.coords.find().forEach(function(doc) {
        var id = doc._id,
            coords = doc.point.coordinates.split(", ");
    
        db.coords.update({ "_id" : id }, { $set : { "point.loc.type": "Point", "point.loc.coordinates": [ coords[0], coords[1] ] } });
    });
    
    // Unset the old field from all the documents
    db.coords.update({}, { $unset: { "point.coordinates" : 1 } }, { "multi": true });
    

答案 1 :(得分:0)

MongoDBs字符串操作不够先进,无法在数据库上完全执行此操作,因此您必须使用MongoDB shell中的一个小程序来完成此操作。或者,您可以使用您喜欢的具有MongoDB驱动程序的编程语言来完成此操作。

  1. 进行空db.collection.find()查询以获取光标集合中的每个文档
  2. 对于您找到的每个doucment,将坐标字段中的字符串拆分为浮点值数组
  3. save将文档返回集合(save函数将搜索具有相同_id的文档并更新它,如果没有找到它会创建一个新文档,这在您的情况下不会发生,因为你从数据库中获得了_id)
相关问题