创建地理空间索引注意事项
创建地理空间索引失败,提示错误信息如下
> db.places.ensureIndex({"loc":"2dsphere"})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"ok" : 0,
"errmsg" : "Can't extract geo keys from object, malformed geometry?: { _
id: ObjectId('5428bb224f26d9aa1af3d844'), name: "Hudson River", loc: { type:
"Line", coordinates: [ [ 0.0, 1.0 ], [ 0.0, 2.0 ], [ 1.0, 2.0 ] ] } }",
"code" : 16755
}
原因是多边形的点至少是4个才能创建成功
mongodb版本:mongodb-2.6。
> db.world.insert( { "name":"New England", "loc":{ "type":"Polygon", "
coordinates":[[0,1],[0,2],[1,2]] } } )这里只有3个点, 最外侧应该有两个[和]
> db.world.insert({"name":"New England", "loc":{ "type":"Polygon", "
coordinates":[[[0,1],[0,2],[1,2],[0,1]]]}})这里有4个。
创建成功提示信息如下:
> db.places.ensureIndex({"loc":"2dsphere"})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
这种错误一般都是json格式和内容不正确。
错误信息如下
"$err" : "Can't canonicalize query: BadValue bad geo query"
原因是type=Polygon类型,表示是多边形,至少需要有4个点(起点和终点必须一样),并且多边形有多个环组成,所以应该是数组结构,每个数组是一个多边形。
正确的格式如下:
db.places.insert({"name":"New England","loc":{"type":"Polygon","coordinates":[[[0,1],[0,2],[1,2],[0,1]]]}})
var eastVillage={"type":"Polygon","coordinates":[[-73.9917900,40.7264100],[-73.9917900,40.7321400],[-73.9829300,40.7321400],[-73.9917900,40.7264100]]}
参考文档如下:
http://stackoverflow.com/questions/25893415/mongodbcant-canonicalize-query-badvalue-bad-geo-query