Sort by $ geoWithin geospatial query in MongoDB

I am trying to get a bunch of polygons stored inside my db and sort them by radius. So I wrote a simple query $geoWithin.

So, without sorting, the code looks like this:

db.areas.find(
   {
       "geometry" : {
          "$geoWithin" : {
              "$geometry" : {
                    "type" : "Polygon",
                    "coordinates" : [ [ /** omissis: array of points **/ ] ] 
                }
            }
        }
    }).limit(10).explain();

And the result of the explanation is as follows:

{
    "cursor" : "S2Cursor",
    "isMultiKey" : true,
    "n" : 10,
    "nscannedObjects" : 10,
    "nscanned" : 367,
    "nscannedObjectsAllPlans" : 10,
    "nscannedAllPlans" : 367,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 2,
    "indexBounds" : {

    },
    "nscanned" : 367,
    "matchTested" : NumberLong(10),
    "geoTested" : NumberLong(10),
    "cellsInCover" : NumberLong(27),
    "server" : "*omissis*"
}

(Even if it is fast, it displays as a cursor S2Cursor, letting me know that my composite index was not used, however it is fast)

So, whenever I try to add a command sortsimply using .sort({ radius: -1 }), the request becomes extremely slow:

{
    "cursor" : "S2Cursor",
    "isMultiKey" : true,
    "n" : 10,
    "nscannedObjects" : 58429,
    "nscanned" : 705337,
    "nscannedObjectsAllPlans" : 58429,
    "nscannedAllPlans" : 705337,
    "scanAndOrder" : true,
    "indexOnly" : false,
    "nYields" : 3,
    "nChunkSkips" : 0,
    "millis" : 3186,
    "indexBounds" : {

    },
    "nscanned" : 705337,
    "matchTested" : NumberLong(58432),
    "geoTested" : NumberLong(58432),
    "cellsInCover" : NumberLong(27),
    "server" : "*omissis*"
}

with MongoDB scanning all documents. Obviously, I tried to add a composite index like { radius: -1, geometry : '2dsphere' }or { geometry : '2dsphere' , radius: -1 }, but nothing helped. Still very slow.

, , S2Cursor -, , , .

(PS: MongoDB 2.4.5+, , 2dsphere, https://jira.mongodb.org/browse/SERVER-9647)

+4
1

, s2Cursor , . , , , , , , .

-2

All Articles