mongodbgeospatialbigchaindb

What is the correct way to query this document? (If the index is correct)


I've a BigChainDB docker container running in my machine and I'm trying to store and retrieve geospatial data. I've created through the MongoDB interface a 2dsphere index "location" in the "metadata" collection. I've checked with the command:

db.people.getIndexes()

And I think that everything it's ok, in fact the result is this:

    {
        "v" : 2,
        "key" : {
            "loc" : "2dsphere"
        },
        "name" : "loc_2dsphere",
        "ns" : "bigchain.metadata",
        "2dsphereIndexVersion" : 3
    }

The document that I've inserted to try some spatial queries is (this is the result of a db.metadata.findOne() query):

{
    "_id" : ObjectId("5ccab10a2ce1b70022823a0f"),
    "id" : "752ee9abccf83c7fd25d86c9a7d12229ae292fa27544f6881f1dbf97ccd8b413",
    "metadata" : {
        "location" : {
            "type" : "Point",
            "coordinates" : [
                22.170872,
                113.578749
            ]
        }
    }
}

But when I use this spatial query nothing is retrieved:

db.metadata.find(
{ 
"metadata": {
     "location": {
       $near: {
         $geometry: {
            type: "Point" ,
            coordinates: [ 22 , 113 ]
         },
       }
     }
  }
})

I'm doing anything wrong, or is there the possibility that the index doesn't work?


Solution

  • There are a couple of issues here.

    The first is that the index is on the field loc whereas your query is querying metadata.location.

    If you try creating a 2dsphere index on metadata.location you will see the 2nd error:

    "errmsg" : "invalid point in geo near query $geometry argument: { type: \"Point\", coordinates: [ 22.0, 113.0 ] }  longitude/latitude is out of bounds, lng: 22 lat: 113",
    

    This error shows that the GEOJSON point defined in your document is invalid, as the latitude value of 113 is outside the acceptable range of [-90, 90].

    You would need to correct the data to be valid GEOJSON before indexing.