How to find a nearby location with latitude and longitude in Mongobba?
I am very new to mongodb and golang. I have a collection called "myplace". It has the following names: place_name, city, latitude, longitude. My question is a user in some place and search for nearby places. How can I query mongodb to find nearby by location. Also in golang.
The structure of my document
{
"_id" : ObjectId("544a2147785b707b340ed6c7"),
"latitude" : 12.36547,
"longitude" : 1.235689,
"place_name" : "some_place",
"city" : "Some city"
}
Thank you in advance
source to share
Hey. In your case, I think you should change the above doc as shown below.
{
"_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
}
}
After that indexing the above documents below
db.collectionName.ensureIndex({loc:"2d"})
If correct indexing is done, write the following query to find out next to the docs
db.location.find({loc: {$near:[51,-114]}})
for more help you should send this mongo $ near and $ geoNear click here
and sorry for golang because I don't know about golang anymore
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)
source to share
This link can help you https://github.com/mendrugory/Airports
MongoDB query (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)
Structure
json is the following:
{"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}
source to share