Store location data in Mongodb document

南楼画角 提交于 2020-01-24 22:58:26

问题


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"
        }
    }

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

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

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?


回答1:


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" }
])

Then create an index on location field

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


来源:https://stackoverflow.com/questions/59895518/store-location-data-in-mongodb-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!