0

I am designing a cab booking service using MongoDB. My schema looks like -

{
    "_id": {
        "$oid": "621ca96e2c7e7efcfba6ce34"
    },
    "registration_id": "Id1",
    "location": [{
        "$numberDouble": "13.197827893722762"
    }, {
        "$numberDouble": "77.70575957707639"
    }]
}

where location is Point GeoJson datatype.

Based on customer's location, I have to provide nearest cab when he makes request. I am using $near query for the same.

query = {"location": { "$near": { "$geometry": { "type": "Point", "coordinates": [event['longitude'], event['latitude']] }}}}

However I need to provide only cabs that belong to given area, defined by 4 co-ordinates.

If I use $geowithin, which provides points defined by area, i wont get sorted results, if I use $near like above, I am not able to limit area.

What is the elegant way to achieve this?

1 Answers1

0

This is very similar to Determine distance from coordinates after aggregation match but the nuance is that it might not be obvious that the query option for $geoNear can itself support geoWithin:

bbox = [[
    [-74, 41],
    [-74, 42],
    [-72, 42],
    [-72, 41],

    [-74, 41] // close the loop                                                                
]];

db.foo.aggregate([
    {$geoNear: { // assume field 'pt' because the 2dsphere index is on that                    
        near: {
            type: "Point",
            coordinates: [tpt[0],tpt[1]]
        },
        maxDistance: 1200,  // whatever you like                     
        distanceField: "distance",
       
        // Now, for the sorted-by-distance items that are returned, further
        // filter by a polygon boundary:                                           
        query: {
            'pt': {'$geoWithin': {'$geometry': {'coordinates': bbox, 'type': 'Polygon'}}}
        }
    }}
]);
Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33