Search code examples
mongodbmongodb-indexes

Create 2dsphere index of polygon in subfield


I'm having problems creating a 2dsphere index in MongoDB 3.6. I have a series of polygons in GeoJSON. One of the polygons is the following example (simplified to just 4 points):

GeoJSON { "_id" : ObjectId("5a92b5ad370dfa460e07f2ab"), "type" : "FeatureCollection", "crs" : { "type" : "name", "properties" : { "name" : "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features" : [ { "type" : "Feature", "properties" : { "ManCatID" : NumberInt(3075), "ManCatName" : "Field1" }, "geometry" : { "type" : "Polygon", "coordinates" : [ [ [ -2.590805067250554, 52.57471588485983 ], [ -2.594339050478125, 52.57415879313657 ], [ -2.590791776038, 52.573727037479124 ], [ -2.590805067250554, 52.57471588485983 ] ] ] } } ] }

When trying to create the 2dsphere index as explained in the official website example, I need to use the subfield 'features.geometry.coordinates'. However, it fails when I try to create with db.CaseStudies.createIndex({ features.geometry: "2dsphere" });.

If I use db.CaseStudies.createIndex({ geometry: "2dsphere" }) I obtain no error. However, when I do a query, I always obtain 'null' results. The query I'm using is:

db.CaseStudies.findOne({ geometry: { $geoIntersects: { $geometry: { type: "Point", coordinates: [ -2.592, 52.574 ] } } } });

Do anyone knows what am I doing wrong?


Solution

  • Can you try using this query instead?:

    db.CaseStudies.findOne({
      "features.geometry": {
         $geoIntersects: { $geometry: { type: "Point", coordinates: [ -2.592, 52.574 ] } }
      }
    });
    

    The field on which you match should be features.geometry instead of geometry.


    Concerning the failure when creating the index, can you try with quotes around features.geometry:

    db.CaseStudies.createIndex({ "features.geometry": "2dsphere" });