Search code examples
mongodbmongoosepolygongeojsonpoint

$centerSphere is not returning any geojson polygons (mongoDB)


I am having a lot of trouble with the following Mongo query

location: { $geoWithin: { $centerSphere: [[lon,lat],radians] } }

It only returns geoJSON Points and ignores all my geoJSON Polygons for some reason. The documentation states:

You can use the $centerSphere operator on both GeoJSON objects and legacy coordinate pairs.

I am using Mongoose to run the queries and my geoJSON is coverted from WellKnown Text by the NPM module wellknown. This is how my geoJSON looks after the wellknown module has converted them:

 "location": {
    "coordinates": [
        22.1,
        33.3
    ],
    "type": "Point"
}

and

"location": {
    "coordinates": [
        [
            [
                43,
                30
            ],
            [
                40,
                28
            ],
            [
                49,
                27
            ],
            [
                43,
                30
            ]
        ],
        [
            [
                44,
                28
            ],
            [
                44.7,
                28.8
            ],
            [
                46,
                28
            ],
            [
                44,
                28
            ]
        ]
    ],
    "type": "Polygon"
}

My Mongoose schema is defined as:

location: {
  type: schema.Types.Mixed,
  index: '2dsphere',
  required: false
}

I should add that the withinPolygon methods work as expected and I get both the Points and Polygons returned. The following works completely fine:

location: { $geoWithin: { $geometry: geoJSON } }

Thank you for any help. I have read the documentation and can't see anywhere where it mentions that the $centerSphere only returns geoJSON Points.


Solution

  • With the recent release of MongoDB version 3.6.0-rc0, you can now query GeoJSON LineStrings and Polygons with $geoWithin geospatial operator $centerSphere.

    See also SERVER-27968 more information about the update.