MongoDB geospatial index on point array

Viewed 35

I want to create a 2dsphere index on an array of (variable number of) points so that I can get the documents having at least one point within a given radius, and also the point(s) in the array that matched.
A document would look like this.

{
  "locations": [
    {
      "type": "Point",
      "coordinates": [8.17, 47.09]
    },
    {
      "type": "Point",
      "coordinates": [8.27, 48.09]
    },
    {
      "type": "Point",
      "coordinates": [8.37, 47.09]
    }
  ]
}

I want to create the index like this:

db.test.createIndex({ "locations": "2dsphere" })

But it fails to create the index on these points. However, if I do

db.test.createIndex({ "locations.coordinates": "2dsphere" })

it (probably) assumes legacy coordinate pair syntax and creates the index. Also, if I do

db.numbers.createIndex({ "thisIsANumberArray": 1 })

for an array of numbers, it creates a multi-key index and works as intended as well.
What am I missing? Or is it how it is with MongoDB?

Now, the second method has the functionality I need, but I want to make sure if there is any disadvantage of doing that.

I tried using "MultiPoint"s like below too -- concise; however, it's hard to get the point(s) that matched.

{
  "locations": {
      "type": "MultiPoint",
      "coordinates": [[8.17, 47.09], [8.27, 48.09], [8.37, 47.09]]
  }
}

Thanks in advance.

0 Answers
Related