1

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?

Jumy Elerossë
  • 189
  • 2
  • 3
  • 12
  • It would be helpful to include the specific error message. It looks like you have a syntax error when creating the index: `features.geometry` should be quoted. – Stennie Feb 25 '18 at 19:44

1 Answers1

1

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" });
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
  • Using the quotes around `features.geometry` gives no error, but using the suggested query still return null results... – Jumy Elerossë Feb 25 '18 at 19:48
  • Sorry forgot to change the collection name I used to test. Is it better? – Xavier Guihot Feb 25 '18 at 19:51
  • Yes, I noticed and it was not working. However, I deleted the collection and added just the single point I gave as an example and it works. I think I was querying out of the shape I had stored. Thank you very much, Xavier. You solved the problem :D – Jumy Elerossë Feb 25 '18 at 19:54