Vish511
Vish511

Reputation: 96

Geospatial query for legacy coordinate pairs

{
"_id" : ObjectId("5b8cfdc5a4788ace69dfe8avc"),
"userName" : "CAN_020704",
"source" : "web",
"contactDetails" : {
    "phone" : NumberLong(0),
    "email" : "",
    "address" : "",
    "city" : "",
    "state" : "",
    "district" : "",
    "subDistrict" : "",
    "pinCode" : 0.0,
    "constituency" : "",
    **"location" : {
        "longitude" : 80.250875,
        "latitude" : 13.052519
    },**
},
"educationalDetails" : [ 
    {
        "education" : "5th to 8th",
        "specialization" : "",
        "passingYear" : 0.0,
        "document" : ""
    }
],
"coursePreferences" : [ 
    {
        "sector" : "Apparel",
        "sectorId" : "2",
        "subSector" : "Fashion Design",
        "subSectorId" : "2",
        "jobRole" : "bdfbv",
        "qpCode" : "QWE/Q2345",
        "createdDate" : ISODate("2018-08-22T05:22:59.800Z")
    }
],
"certifications" : [],
"visibleTo" : [],
"createdBy" : "",
"sdmsFinancialYear" : ""
}

I have my location data saved as legacy coordinate pairs inside contactDetails object. I have used 2dsphere index { "contactDetails.location" : "2dsphere" }

db.geo.find({"contactDetails.location": {"$near" : [80.248797,13.050599],"$maxDistance":0.005}},{"contactDetails.location":1,"contactDetails.state":1}) This is my query. But, Mongo shell is throwing an error.

Error: error: { "ok" : 0, "errmsg" : "error processing query: ns=ekaushalnsdc.geoTree: GEONEAR field=contactDetails.location maxdist=0.005 isNearSphere=0\nSort: {}\nProj: { contactDetails.location: 1.0, contactDetails.state: 1.0 }\n planner returned error: unable to find index for $geoNear query", "code" : 2, "codeName" : "BadValue" } I get it that something is wrong with my index. It works if I specify a 2d index but doesn't if I index the collection based on 2dsphere index. My requirement is to find all the documents within a distance of 1km from the coordinates given in the query.

Upvotes: 0

Views: 477

Answers (1)

Vish511
Vish511

Reputation: 96

After doing some research, found out that to query a 2dsphere index, the query should be of the following form :

 db.geo.find( { "contactDetails.location" :
                     { $near :
                       { $geometry :
                          { type : "Point" ,
                            coordinates : [80.248797,13.050599] } ,
                         $maxDistance : 1000
                  } } } )

This gives accurate results.

Upvotes: 1

Related Questions