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

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

本文介绍了如何在mongodb中找到经纬度附近的地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我的文档结构

  {
_id:ObjectId(544a2147785b707b340ed6c7),
latitude:12.36547,
longitude:1.235689,
place_name:some_place,
city :某城市
}

预先致谢 $ b $ code> {
_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



对于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}})。 ;地点)


Am very new to mongodb and golang. I have a collection named "myplace" It has the following fileds place_name, city, latitude, longitude. My question is user in some place and searching the nearby places. How can I query to mongodb to find near by locations. Also in golang.

My doc structure

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

Thanks in advance

解决方案

Hi For your case I think you should changed above doc as 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 as below

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

If indexing executing properly then write following query to find out near by documents

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

for more help you should refer this mongo $near and $geoNear click here

and sorry for golang because I don't know more about 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)

这篇关于如何在mongodb中找到经纬度附近的地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:47