我的mongo版本是3.2.6
我的餐桌是restaurant_locations。
我给出的指数如下:
db.restaurant_locations._ensureIndex({'location': '2dsphere'});
此表中存储的数据如下:
> db.restaurant_locations.find().pretty();
{
"_id" : ObjectId("573ff477df3c12bdd6463d07"),
"location" : {
"type" : "Point",
"coordinates" : [
72.5220332,
23.0656791
]
}
}
{
"_id" : ObjectId("573ff5badf3c12bdd6463d08"),
"location" : {
"type" : "Point",
"coordinates" : [
62.5220332,
13.0656791
]
}
}
现在当我在查询下面开火时:
db.restaurant_locations.find({
location: {
$near: {
$geometry: {
type: 'Point',
coordinates: [ 70, 20 ]
},
$maxDistance: 100000000
}
}
});
我得到两个记录作为输出:
{ "_id" : ObjectId("573ff477df3c12bdd6463d07"), "location" : { "type" : "Point", "coordinates" : [ 72.5220332, 23.0656791 ] } }
{ "_id" : ObjectId("573ff5badf3c12bdd6463d08"), "location" : { "type" : "Point", "coordinates" : [ 62.5220332, 13.0656791 ] } }
现在,当我执行以下查询时:
db.restaurant_locations.find({
location: {
$near: {
$geometry: {
type: 'Point',
coordinates: [ 70, 20 ]
},
$maxDistance: 1000000
}
}
});
我只输出一条记录:
{ "_id" : ObjectId("573ff477df3c12bdd6463d07"), "location" : { "type" : "Point", "coordinates" : [ 72.5220332, 23.0656791 ] } }
我已经提到了许多mongodb文档,stackoverflow问题,但我没有得到确切的想法,它是如何工作的
提前感谢您的帮助
答案 0 :(得分:0)
I am not getting exactly how $maxDistance work.
为了获得maxDistance工作,您必须使用$nearSphere
函数
您的查询将是这样的:
location: {
$nearSphere: {
$geometry: {
type: 'Point',
coordinates: [ 70, 20 ]
},
$maxDistance: 10000
}
}
I want to find restaurants within a distance of 10 kms,
你需要乘以1000,因为mongo分辨率以米为单位
Suppose my co-ordinates are 40 and 20, so if I want restaurants within 10kms, will above two records display?
是的,但您必须先确定先指定经度,然后再指定纬度。