Mongo DB – 具有位置和场半径的地理空间查询(内部字段比较)

在我的项目中有两个要求

第一个 :我有下面的集合

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

为此,我必须find与我的位置相匹配的所有位置,以便使用此查询:

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

上述查询工作正常。

第二个 :我有下面这个集合,我面临问题。

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

在这里我有我的collections本身的半径。 用户input仅为loc

 var myLoc = [ 14.67, 56.78 ]; 

现在我必须find与我的位置和他们的位置和半径相匹配的所有文件。

我曾试过类似的查询

 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" 

然后

 model .find( { $where: { Location : { $geoWithin : { $centerSphere : [myLoc, '$Radius'] } } } } ) .exec() Error : Error: Must have a string or function for $where 

然后

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

错误:err是MongoError:exception:bad查询:BadValue错误的地理查询:{$ geoWithin:{$ centerSphere:[[-1.965373600000021,52.4744464],“$ Radius”]}}

我对mongodb查询是相当新的。即使你的小build议会帮助我很好的方式。 请给我如何实现这一点的见解。 非常感谢您的帮助。谢谢

您可以使用$where操作符:

 model.find({'$where': function() { var myLoc = [ 14.67, 56.78 ]; return { 'loc': { '$geoWithin': { "$centerSphere": [ myLoc, this.Radius ] } } }} })