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



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

[_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" ] }"

我错过了什么?任何帮助将不胜感激!提前谢谢。

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

"_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})

希望对您有所帮助!

最新更新