问题
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