Mongo Bounding Box Query with Limit

跟風遠走 提交于 2019-12-24 03:19:39

问题


We are using mongo (via pymongo) to store a database of points in our system. This data is returned via our api using bounding box queries ($geoWithin).

We want to limit the number of results returned to 200 sorted from the center. I'm trying to figure out the best way to do this. Currently, we get all items (no limit). Then, we calculate distance and sort in python. However, that those calculations very slow and memory intensive for large datasets.

Anyone have better suggestions? I see in other SO questions that it isn't possible to sort bounding box queries. However, most of those questions were 2+ years old.


回答1:


Alright, I think I figured out a solution. Turns out that you can use both a point/radius and bounding box in the same query.

    # do both a bounding box and point query
    # point query should conatain the entire bbox
    # this provides sorting and distance calculations
    max_distance = int(haversine(sw_lat, sw_lon, self.centroid.y, self.centroid.x))
    self.new_query = {
        '$and': [
            {'point': {
                '$geoWithin': {"$box": box }
            }},
            {'point': OrderedDict([
                ('$geoNear', {
                    '$geometry':  {
                        'type': 'Point' ,
                        'coordinates': [self.geo.centroid.coords[0], self.geo.centroid.coords[1]]
                    },
                    '$maxDistance': max_distance
                }),

            ])}
        ]
    }


来源:https://stackoverflow.com/questions/29016437/mongo-bounding-box-query-with-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!