Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB - Geospatial Queries with location and field radius(Internal field comparision)

In My project there are two requirements

First One : I have the collection below

{
   "name": "James",
   "loc" : [ 12.9000, 14.6733]
},
{
   "name": "James",
   "loc" : [ 54.9000, 78.6733]
}

For this I have to find all the location which match my location with a particular radius so I use this query:

var myLoc     = [ 13.5,  67.5 ];
var myRadius  = 150;
model.find({
        loc : {
            $geoWithin : {
                $centerSphere : [ myLoc, myRadius ]
            }
        }
    }
).exec()

The above query is working fine.

Second One : I have the collection like below.here i am facing problem.

{
   "name"   : "James",
   "loc"    : [ 12.9000, 14.6733],
   "radius" : 115
},
{
   "name"   : "James",
   "loc"    : [ 54.9000, 78.6733],
   "Radius" : 276
}

Here i have the radius in my collection itself. The user input is loc only

var myLoc = [ 14.67, 56.78 ];

Now I have to find all the documents which match my location with their location and their radius.

I have tried queries like

model
.where('loc').within({ center: myLoc, radius: 'this.Radius', unique: true, spherical: true })
.exec()

Error : The err is CastError: Cast to number failed for value "this.Radius" at path "undefined"

then

model
    .find(
        {
            $where: 
                {
                    Location : { 
                        $geoWithin : 
                            { $centerSphere : [myLoc, '$Radius'] }
                        }
                }
        }
    )
    .exec()


Error : Error: Must have a string or function for $where

then

model
    .aggregate( 
        { 
            $match : {
                loc : {
                    $geoWithin : {
                        $centerSphere : [ myLoc, "$Radius" ]
                    }
                }   
            }                                       
        }
     )
    .exec(  )

Error : The err is MongoError: exception: bad query: BadValue bad geo query: { $geoWithin: { $centerSphere: [ [ -1.965373600000021, 52.4744464 ], "$Radius" ] } }

I am quite new to mongodb query..Even your little suggestion will help me in a great way. Please give me the insight on how to achieve this. your help is greatly appreciated.Thanks

like image 690
sdg Avatar asked Nov 27 '15 09:11

sdg


1 Answers

You can use the $where operator:

model.find({'$where': function() {
    var myLoc = [ 14.67, 56.78 ];
    return { 'loc': { 
        '$geoWithin': { "$centerSphere": [ myLoc, this.Radius ] } }
    }}
})
like image 125
styvane Avatar answered Nov 15 '22 05:11

styvane