如何在mongodb中找到经纬度附近的地方?

时间:2014-11-03 08:20:44

标签: mongodb go mgo

对mongodb和golang来说很新。我有一个名为" myplace"它有以下文件place_name,city,latitude,longitude。我的问题是用户在某个地方并搜索附近的地方。如何查询mongodb以查找附近的位置。也在golang。

我的文档结构

{
    "_id" : ObjectId("544a2147785b707b340ed6c7"),
    "latitude" : 12.36547,
    "longitude" : 1.235689,
    "place_name" : "some_place",
    "city" : "Some city"
}

提前致谢

2 个答案:

答案 0 :(得分:7)

嗨,对于您的情况,我认为您应该更改为以下文档

    {
    "_id" : ObjectId("545749dba2b0b4cf603a7546"),
    "city" : "B",
    "placeName" : "A",
    "loc" : {
        "lon" : 51.10682735591432,
        "lat" : -114.11773681640625
    }
}
{
    "_id" : ObjectId("545749f3a2b0b4cf603a7547"),
    "city" : "B1",
    "placeName" : "A1",
    "loc" : {
        "lon" : 51.09144802136697,
        "lat" : -114.11773681640625
    }
}

之后索引上述文件如下

db.collectionName.ensureIndex({loc:"2d"})

如果索引正确执行,则编写以下查询以查找文档附近

db.location.find({loc: {$near:[51,-114]}})

要获得更多帮助,请参考此mongo $ near和$ geoNear click here

抱歉golang,因为我不太了解golang

for golang

var places []Place
lat := 51.515614
long := -0.268998
err = coll.Find(bson.M{"loc": bson.M{"$near": []float64{long, lat}, "$maxDistance" :      0.056}}).All(&places)

答案 1 :(得分:2)

此链接可能会对您有所帮助https://github.com/mendrugory/Airports

MongoDB查询(python)

def get_closest_airports(lonlat, limit=10):
    """
    Using a raw query it returns the "limit" closest airports.

    :param latlon list:
    :return list of airports:
    """
    return Airport.objects(
        __raw__={"loc": {"$near": {"$geometry": {"type": "Point", "coordinates": lonlat}}}}).limit(limit)

json结构如下

{"city": "Goroka", "tz": "Pacific/Port_Moresby", "name": "Goroka", "dst": "U", "loc": {"type": "Point", "coordinates": [145.391881, -6.081689]}, "country": "Papua New Guinea", "iata/faa": "GKA", "altitude": 5282.0, "icao": "AYGA", "timezone": 10.0, "id": 1}