在多个框上使用$ geowithin - mongoDB

时间:2014-04-25 08:09:22

标签: mongodb mongoose pymongo geojson aggregation-framework

我需要搜索位于框中的所有点。所以我在mongoDB中使用以下查询

db.places.find({ 
    "loc" : { 
        "$geoWithin" : { 
            "$box": [ 
                [ 0 , 0 ] ,
                [ 100 , 100 ]
             ] 
         }
     } 
})

现在我要在其中搜索多个框,我想获得任何框中的所有点。我想要像

这样的东西
db.places.find({ 
    "loc": { 
        "$geoWithin": { 
            "$box":[ [ 0 , 0 ], [ 25 , 25 ] ],
                [ [ 40 , 40 ] , [ 75 , 75 ] ],
                [ [ 90 , 90 ] , [ 100 , 100 ] ] 
         }
     }
})

我无法使用$or进行短路评估。我也不能使用聚合,因为聚合仅支持$geonear。我不想为每个框打一个单独的查询。请建议。

1 个答案:

答案 0 :(得分:1)

有一些“快捷”类型的运算符可用于预定义的“geo”类型查询,例如 $box 。但是对于任何更高级的东西,您实际上都想要正式声明GeoJSON结构并使用 $geometry 运算符:

因此,如果您考虑以下文件:

{ "loc" : { "type" : "Point", "coordinates" : [ 3, 6 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 9, 12 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 45, 45 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 30, 30 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 76, 76 ] } }

然后使用以下查询:

db.geo.find({
    "loc": {
        "$geoWithin": {
            "$geometry":{
                "type": "MultiPolygon",
                "coordinates": [
                    [[ [ 0, 0 ], [ 0, 25 ], [ 25, 25 ], [ 25, 0 ], [ 0, 0 ] ]],
                    [[ [ 40, 40 ], [ 40, 75 ], [ 75, 75 ], [ 75, 40 ], [ 40, 40 ] ]],
                    [[ [ 80, 80 ], [ 80, 90 ], [ 90, 90 ], [ 90, 80 ], [ 80, 80 ] ]]
                ]
            }
        }
    }
})

您将获得返回的结果:

{ "loc" : { "type" : "Point", "coordinates" : [ 3, 6 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 9, 12 ] } }
{ "loc" : { "type" : "Point", "coordinates" : [ 45, 45 ] } }

因此,对于此类查询,您需要完全支持GeoJSON几何体。

这绝对适用于MongoDB 2.6,也应该是2.4.10的情况。扩展的GeoJSON类型可用于这些版本的索引,但(未尝试)可能在早期的2.4版本中用作查询形式。

相关问题