问题
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