简体   繁体   中英

mongodb $geoIntersects or $geoWithin a point matches multiple polygons - sort by area?

I have a mongo query that checks to see if a point is within a polygon.

neighborhood =  db.collection.findOne({
    loc: {$geoInteresects: {$geometry: {
        type: 'Point',
        coordinates: [lng, lat]
    }}}
})

Currently, all of my polygons are just a single level, a neighborhood, and none of them overlap.

I'd like to start storing city, county, and country data in the same collection. Obviously, I can change the findOne to a find and modify the code appropriately, but, in particular, I want the results to sort the matches, so that results are: [ "Downtown", "San Francisco", "California", "US", "North America"]

and it's trivial for me to build a nice string out of that.

I do -not- have my multi-level polygons set up yet, so I have not tested.

I know that the $near operator returns the nearest points to an object, and can sort, but my assumption, from reading the documentation, is that since my test point is within the polgyon, the sort order would be undefined, and I also run the risk of getting nearby polygons as well, that I would then have to check with a second geointersects to make sure we're not inside them.

So I solved this in a different way. Calculating the areas of geography objects should be done ahead of time, when populating the index.

I wrote code to calculate area and bounds for each polygon and insert in the collection, so a conventional sort can be used, along with its indexes.

db.collection.find({
    loc: {$geoInteresects: {$geometry: {
    type: 'Point',
    coordinates: [lng, lat]
}}}).sort({'properties.area': 1})

will always give the smallest polygon that we match. It would be lovely if Mongo could do this, but since it can be a computationally expensive operation, even with the trapezoid model, it should be done once at insert, not ever time at lookup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM