How do I find 25 evenly spaced documents in a bounding box?

I have a set of documents with a location field. I need to find documents in a bounding box and limit the number of resulting documents (say 25). But I also need those 25 documents that are evenly spaced across the entire bounding box (not just 25 random documents). Is there a way I can achieve this using MongoDB?

+3


source to share


1 answer


With a bit of math and thinking, you can get the "nearby" items to the center of the box. Requires multiple operations from the original query with some help from the aggregation framework.

Suppose the start margin is (0,0) and the maximum edge is (4,4), making the center (2,2). Then you will select the following:

db.collection.aggregate([
    // Find results near to the centre of the box
    { "$geoNear": {
        "near": {
            "type": "Point",
            "geometry": [2,2]
        },
        "maxDistance": 4,        // limit a bit outside the boundary
        "distanceField": "dist"  // Projected field with distance
    }},

    // Filter out results outside the box
    { "$match": {
        "$geoWithin": {
            "box": [
                [0,0],
                [4,4]
            ]
        }
    }},

    // Sort by distance
    { "$sort": { "dist": 1 } }

    // Limit the results
    { "$limit": 25 }
])

      



So the basic principle. Take note to really consider which coordinate system you are using and whether the data is stored in legacy or GeoJSON format as this affects the distance projected as documented.

But it essentially finds functions that fall "close" to the center of the window, which you will describe later. Most importantly, it "projects" a field representing the "distance" from the requested point. Then it matches those elements that actually fall into the field. $geoNear

$geoWithin

It remains only to the nearest records, then the final results do not exceed 25 from the nearest record. $sort

$limit

0


source







All Articles