【问题标题】:MongoDB: Geospatial Index array not in correct formatMongoDB:地理空间索引数组格式不正确
【发布时间】:2012-02-02 01:14:52
【问题描述】:

在尝试设置以在 MongoDB 上使用地理空间索引时,我遇到了位置数组格式不正确的错误消息。

这是我的收藏“测试”。

{
    "_id" : ObjectId("4f037ac176d6fdab5b00000a"),
    "CorporateId" : "XYZ12345",
    "Places" : [
           {

                   "Location" : {
                           "Longitude" : "50.0",
                           "Latitude" : "50.0"
                   },
                   "ValidFrom" : "2011-11-01 00:00:00",
                   "ValidTo" : "2021-12-31 00:00:00",
                   "itemCount" : "1"
           }
    ]
}

一旦我运行了这段代码。

db.test.ensureIndex({"Places.Location": "2d"});

我收到此错误消息

需要位置对象,位置数组格式不正确

我的假设是 Long/Lat 需要是一个数字。 目前它是一个对象。

typeof db.test.Places.Location.Longitude -> Object
typeof db.test.Places.Location -> Object

我的问题是,由于我对 MongoDB 还很陌生,我真的不知道如何以最好的方式解决这个问题。

【问题讨论】:

  • 您使用的是什么客户端应用程序?
  • 是的,它必须是一个数字。

标签: mongodb geospatial


【解决方案1】:

通过将 Location 参数转换为像这样的浮点类型,问题已得到解决。

$var = $JSonString['Places'];
 $test=count($var);

 $i=0;
 for ( $i=0; $i<$test;$i++){
       $lon = (float)$JSonString['Places'][$i]['Location']['Longitude'];
       $lat = (float)$JSonString['Places'][$i]['Location']['Latitude'];
       $JSonString['Places'][$i]['Location']['Longitude'] =$lon ;
       $JSonString['Places'][$i]['Location']['Latitude'] =$lat ;
       //error_log($lon . "->".gettype($JSonString['Places'][$i]['Location']['Latitude']), 3 , "/var/tmp/my-errors.log");
 }

【讨论】:

    【解决方案2】:

    当你传入一个字符串时,Mongodb 期望坐标的数字。

    "Location" : {
                           "Longitude" : 50.0, // <<<<<<<<<<<<<< use numbers instead
                           "Latitude" : 50.0
                   },
    

    详情请参阅http://www.mongodb.org/display/DOCS/Geospatial+Indexing

    【讨论】:

    • 感谢您的快速帮助。有没有办法强制集合将其作为数字插入?
    • 您可以使用parseFloat()在插入前将坐标强制转换为数字。
    • 我的问题是插入例程基本上只是将序列化的 json 数组保存到数据库中。这意味着我必须在插入之前解析 JSON 字符串。请原谅我缺乏知识,这是推荐的方法吗?
    • 抱歉,我没有找到其他方法。
    • 是的,您需要解析 JSON(或在上游修复它)。在 Mongo 中无法使用任何类型的模式来强​​制执行此操作。
    猜你喜欢
    • 1970-01-01
    • 2016-02-12
    • 2016-09-14
    • 2011-10-23
    • 2014-01-04
    • 2019-11-30
    • 1970-01-01
    • 2017-01-25
    • 2011-04-22
    相关资源
    最近更新 更多