Search code examples
mongodbgeospatialmongodb-geospatial

mongoDB geospatial query doesn't works


I'm trying to extract all the elements inside a polygon (regular or irregular) but mongoDB geospatial doesn't works.

When I do the query like this, works perfectly

db.getCollection('houses').find({
  'coordinates_geojson.coordinates.1': {
        '$lte': 20.49584842128357,
        '$gte': 20.458539491985142
    },
    'coordinates_geojson.coordinates.0': {
        '$lte': -103.4088134765625,
        '$gte': -103.47747802734375
    }
})

but if try to query using geoWithin, doesn't return me anything

db.getCollection('houses').find({
  "coordinates_geojson": {
    "$geoWithin": {
      "$geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [
                -103.47747802734375,
                20.458539491985142
              ],
              [
                -103.4088134765625,
                20.458539491985142
              ],
              [
                -103.4088134765625,
                20.49584842128357
              ],
              [
                -103.47747802734375,
                20.49584842128357
              ],
              [
                -103.47747802734375,
                20.458539491985142
              ]
            ]
          ]
        ]
      }
    }
  }
})

Any help or idea is welcome


Solution

  • That's the correct answer, first unset the field coordinates_geojson.deviation_level and then build the index db.collection.createIndex({"coordinates_geojson" : "2dsphere" }).
    Thank you @B.Fleming