MongoDB使用单点和半径查找多边形坐标

时间:2014-06-16 12:49:46

标签: mongodb

我有一个包含许多多边形坐标的集合,它代表不同的区域。 我的目标是什么,我将在mongodb查询中发送一个lat,long和radius,它应该返回落在圆圈区域内的多边形坐标。

多边形坐标:

{
    "_id" : "300",
    "name" : "MeKesler",
    "centroid" : [ 
        0, 
        0
    ],
    "type" : "cnbd_id",
    "coords" : [ 
        [ 
            39.8620784017, 
            -86.14614844330004
        ], 
        [ 
            39.8625395793, 
            -86.15442037579999
        ], 
        [ 
            39.8593030353, 
            -86.156373024
        ], 
        [ 
            39.8586935926, 
            -86.15669488909998
        ], 
        [ 
            39.8534225112, 
            -86.15854024890001
        ], 
        [ 
            39.850391456, 
            -86.1589050293
        ], 
        [ 
            39.8511657057, 
            -86.1479830742
        ], 
        [ 
            39.8511986523, 
            -86.14598751070002
        ], 
        [ 
            39.856881704, 
            -86.14605188370001
        ], 
        [ 
            39.8575241063, 
            -86.14605188370001
        ], 
        [ 
            39.8620784017, 
            -86.14614844330004
        ]
    ]
}

我的查询:

db.collection.find({
    "coords" : {
        "$within" : { 
            "$center" : [ 
                [ 39.863110, -86.168456], 
                2/69.1
            ]
        }
    }
}) 

有人可以为此提供帮助吗?

1 个答案:

答案 0 :(得分:2)

我认为问题在于您的文档无效geojson。多边形的有效语法是

{
    "_id": "300",
    "name": "MeKesler",
    "centroid": {
        type: "Point",
        coordinates: [0, 0]
    },
    "type": "cnbd_id",

    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [39.8620784017, -86.14614844330004],
                [39.8625395793, -86.15442037579999],
                [39.8593030353, -86.156373024],
                [39.8586935926, -86.15669488909998],
                [39.8534225112, -86.15854024890001],
                [39.850391456, -86.1589050293],
                [39.8511657057, -86.1479830742],
                [39.8511986523, -86.14598751070002],
                [39.856881704, -86.14605188370001],
                [39.8575241063, -86.14605188370001],
                [39.8620784017, -86.14614844330004]
            ]
        ]
    }
}

此外,您应该考虑在几何字段上创建2dsphere index

最后,地理查询应使用$geoWithin运算符,并针对多边形运行,而不是针对其坐标运行。

db.collection.find({
    "geometry" : {
        "$geoWithin" : { 
            "$center" : [ 
                [ 39.863110, -86.168456], 
                2/69.1
            ]
        }
    }
})