在$ geoWithin MongoDB上应用过滤器

时间:2014-04-24 18:54:01

标签: mongodb gis

我将所有Points,Linestrings和Polygons存储在一个集合中。我可以使用$ geoWithin检索给定多边形内的所有Points和Linestring,如下所示:

db.BLR_all.find(
   {
       "geom" : {
          "$geoWithin" : {
              "$geometry" : {
                    "type" : "Polygon",
                    "coordinates" : [ [ /** array of points **/ ] ] 
                }
            }
        }
    })

如何修改上述查询以仅提取给定多边形中的Point类型?

谢谢

1 个答案:

答案 0 :(得分:1)

您的查询修改实际上非常简单,只需在查询中包含GeoJSON类型的过滤条件:

db.BLR_all.find(
   {
       "geom" : {
          "$geoWithin" : {
              "$geometry" : {
                    "type" : "Polygon",
                    "coordinates" : [ [ /** array of points **/ ] ] 
                }
            }
        },
        "geom.type": "Point"
    })

或者特别是对某些样本数据

{
    "_id" : ObjectId("534cb37acca5f311cc5c23cc"),
    "loc" : {
            "type" : "Polygon",
            "coordinates" : [
                    [
                            [
                                    0,
                                    0
                            ],
                            [
                                    3,
                                    6
                            ],
                            [
                                    6,
                                    1
                            ],
                            [
                                    0,
                                    0
                            ]
                    ]
            ]
    }
}
{
    "_id" : ObjectId("535aeddfb6b8fd04b3424a09"),
    "loc" : {
            "type" : "Point",
            "coordinates" : [
                    3,
                    6
            ]
    }
}
{
    "_id" : ObjectId("535aef22b6b8fd04b3424a0a"),
    "loc" : {
            "type" : "Point",
            "coordinates" : [
                    9,
                    12
            ]
    }
}

发出查询:

db.geo.find({ 
    "loc": { 
        "$geoWithin": { 
            "$geometry": { 
                "type": "Polygon", 
                "coordinates":  [ [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0 ] ] ] 
            } 
        }
    }, 
    "loc.type": "Point" 
})

只返回" Point"并在坐标范围内。

{
    "_id" : ObjectId("535aeddfb6b8fd04b3424a09"),
    "loc" : {
            "type" : "Point",
            "coordinates" : [
                    3,
                    6
            ]
    }
}