嵌套数组字段的Mongodb 2dsphere索引

时间:2014-02-24 06:49:50

标签: php mongodb geolocation indexing geospatial

我创建了集合,对象看起来像这样。

[_id] => MongoId Object (
    [$id] => 53087f483b15eaeb6c3c9869
)
[time_from] => 2014-02-22 00:00:00
[time_to] => 2014-02-22 00:10:00
[checkin] => Array (
    [0] => Array (
        [time_frame] => 2014-02-22 00:00:56
        [user_id] => 1
        [loc] => Array (
            [type] => Point
            [coordinates] => Array (
                [0] => 73.43
                [1] => 42.22
            )
        )
    )
    [1] => Array (
        [time_frame] => 2014-02-22 00:00:56
        [user_id] => 2
        [loc] => Array (
            [type] => Point
            [coordinates] => Array (
                [0] => 73.10
                [1] => 42.97
            )
        )
    )
}

我需要为'loc'字段创建“2dsphere”索引。签入字段具有以数组格式存储的所有位置坐标。

我尝试创建如下索引。

db.<collection>.ensureIndex( { "checkin.loc" : "2dsphere"  } );

我收到以下错误消息。

"err" : "Can't extract geo keys from object, malformed geometry?:{ type: \"Point\", coordinates: [ \"73.10\", \"40.73\" ] }"

我缺少什么?任何帮助,将不胜感激!提前谢谢。

1 个答案:

答案 0 :(得分:4)

您提供的文档看起来不错,我也用简短的文档版本进行了简单的测试,它对我有用。

"_id" : ObjectId("530cb07c009d8c323b477957"),
        "time_from" : ISODate("2014-02-25T15:02:20.714Z"),
        "checkin" : [
                {
                        "user_id" : 1,
                        "loc" : {
                                "type" : "Point",
                                "coordinates" : [
                                        73.43,
                                        42.22
                                ]
                        }
                }
        ]

db.testGeo.ensureIndex( { "checkin.loc" : "2dsphere"  } );

所以我建议检查集合中的其他文档,其中一些文档可能会因索引而格式错误。还要确保坐标数组元素不是字符串。因为此文档对于2dsphere索引无效:

"_id" : ObjectId("530cb07c009d8c323b477957"),
            "time_from" : ISODate("2014-02-25T15:02:20.714Z"),
            "checkin" : [
                    {
                            "user_id" : 1,
                            "loc" : {
                                    "type" : "Point",
                                    "coordinates" : [
                                            "73.43",
                                            "42.22"
                                    ]
                            }
                    }
            ]

请注意坐标元素的引号,使它们成为字符串。

回答评论: Mongo每个集合只允许一个地理空间索引。因此,您不必为runCommand指定整个字段路径。集合名称就足够了。如果集合名称为checkin_20140222

,这应该适合您
db.runCommand( { geoNear: 'checkin_20140222', near: {type: "Point", coordinates: [73.43, 42.22]}, spherical: true, maxDistance: 40000})

希望它有所帮助!

相关问题