Constrained Mongo Constraint Problem

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

We want to limit the number of results returned to 200, sorted by center. I am trying to find a better way to do this. Currently, we receive all items (without restrictions). Then we calculate the distance and sort in python. However, that these calculations are very slow and memory intensive for large data sets.

Does anyone have any better suggestions? In other SO issues, I see that sorting bounding box queries is not possible. However, most of these issues were 2+ years old.

+2
source share
1 answer

Ok, I think I understood the solution. Turns out you can use either a dot / radius or a 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
                }),

            ])}
        ]
    }
+2
source

All Articles