在MongoDB文档中存储位置数据 [英] Store location data in Mongodb document

查看:42
本文介绍了在MongoDB文档中存储位置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我将位置数据以以下格式存储在 Mongodb 文档中

In my current project , I am storing the location data in the following format in a Mongodb document

"location" : {
        "loc" : {
            "lng" : -118.15592692,
            "lat" : 34.03566804
        },
        "geocode" : {
            "city" : "East Los Angeles",
            "state" : "CA",
            "zipcode" : "90022",
            "countrycode" : "US",
            "country" : "United States"
        }
    }

在 location.loc 字段上创建了一个二维索引:-

There is a 2d index created on location.loc field:-

{
    "location.loc" : "2d"
}

但是当结果集很大(即超过 7000 条记录)时,地理空间查询需要很长时间.在我看来,索引不起作用.是不是因为数据没有按格式存储:-

But the geospatial queries are taking long time when the result set is large i.e more than 7000 records. it seems to me that the index is not working . Is it because the data has not been stored in the format:-

loc: [-118.15592692, 34.03566804]

请建议可以做些什么来提高性能?

Please suggest what can be done to improve the performance?

推荐答案

更新您的文档并创建一个新集合

Update your documents and create a new collection

db.location.aggregate([
  { "$addFields": {
    "location": {
      "type": "Point",
      "coordinates": ["$location.loc.lng", "$location.loc.lat"]
    },
    "geocode": "$location.geocode"
  }},
  { "$out": "location" }
])

然后在 location 字段上创建索引

Then create an index on location field

db.location.createIndex({ "location": "2d" })

这篇关于在MongoDB文档中存储位置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆