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

sdg*_*sdg 6 geospatial mongoose mongodb node.js

在我的项目中有两个要求

第一个:我有下面的集合

{
   "name": "James",
   "loc" : [ 12.9000, 14.6733]
},
{
   "name": "James",
   "loc" : [ 54.9000, 78.6733]
}
Run Code Online (Sandbox Code Playgroud)

为此,我必须找到所有匹配我的位置与特定半径的位置,所以我使用此查询:

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

上面的查询工作正常.

第二个:我收藏如下.我面临着问题.

{
   "name"   : "James",
   "loc"    : [ 12.9000, 14.6733],
   "radius" : 115
},
{
   "name"   : "James",
   "loc"    : [ 54.9000, 78.6733],
   "Radius" : 276
}
Run Code Online (Sandbox Code Playgroud)

在这里,我的收藏本身就是半径.用户输入仅为loc

var myLoc = [ 14.67, 56.78 ];
Run Code Online (Sandbox Code Playgroud)

现在我必须找到与我的位置匹配的所有文件及其位置和半径.

我试过像

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"
Run Code Online (Sandbox Code Playgroud)

然后

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


Error : Error: Must have a string or function for $where
Run Code Online (Sandbox Code Playgroud)

然后

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

错误:错误是MongoError:异常:错误查询:BadValue错误的地理查询:{$ geoWithin:{$ centerSphere:[[ - -1.965373600000021,52.4744464],"$ Radius"]}}

我对mongodb查询很新.即使你的小建议也能帮助我.请告诉我如何实现这一目标.非常感谢你的帮助.谢谢

sty*_*ane 1

您可以使用$where运算符:

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