Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB error while implementing $near query

Sample MongoDB Document

{
 "_id":"5adedaad0bd4134kb0",
 "url":"https://iscon.cdnalign.com/t51.288515/s640x640e35/10249200241120_2108192950_n.jpg?ig_cache_key=MTEYUTB1NDgxN",
 "description":"#funinthesun",
 "locationName":"Calamari",
 "statusValue":1,
 "reason":"Related to travel",
 "category":["park"],
 "geo": {
       "index":"Point",
       "coord":[29.123024,77.1999]
  }

}

I wand to get document according to there distance from a particular point.

and this is the query that I am using so that documents come according to distance.

Query
var collection = db.collection('myData');
collection.ensureIndex({"geo.index":"Point"});
collection.find({ 
  geo :{
       $near : {
          $geometry : {   
             index : "Point" ,
             coord : [30.564058, 76.44762696]
          },
       $maxDistance : 100
      }
   }
}

and this is showing me this error :- {"name":"MongoError","message":"invalid point in geo near query $geometry argument: { index: \"Point\", coord: [ 4.27326978424058, 30.4439024447627 ] } Point must be an array or object","waitedMS":0,"ok":0,"errmsg":"invalid point in geo near query $geometry argument: { index: \"Point\", coord: [ 4.27326978424058, 30.4439024447627 ] } Point must be an array or object","code":2}

like image 263
Kunal Nischal Avatar asked Apr 15 '26 12:04

Kunal Nischal


2 Answers

If you check the $near documentation https://docs.mongodb.com/manual/reference/operator/query/near/ you will see that you have two issues here :

  1. You need an index of type 2dsphere in order to make geospacial queries on GPS fields
  2. A geospacial Point must have a property of name coordinates and not coor

Here is a correct version of your code that should works

var collection = db.collection('myData');
collection.ensureIndex({"geo":"2dsphere"});
collection.find({ 
  geo :{
   $near : {
      $geometry : {   
         index : "Point" ,
         coordinates : [30.564058, 76.44762696]
        },
     $maxDistance : 100
    }
  }
})
like image 99
loicmathieu Avatar answered Apr 18 '26 17:04

loicmathieu


https://docs.mongodb.com/manual/reference/operator/query/near/

May be wrong here but from docs $geometry requires two parameters index and coordinates. You have coord. Maybe this is the issue. Change

coord : [30.564058, 76.44762696]

to be

coordinates : [30.564058, 76.44762696]

Also change name in DB too.

Hope this helps.

like image 22
Mykola Borysyuk Avatar answered Apr 18 '26 17:04

Mykola Borysyuk