geolocation - Geonear is not working - mongodb? -
i have following sample mongodb document in collection offers
.
collection : offers
{ "countrycode" : "lu", "geolocation" : [ { "lat" : 49.8914114000000026, "lng" : 6.0950994999999999 } ] }, { "countrycode" : "de", "geolocation" : [ { "lat" : 50.8218536999999984, "lng" : 9.0202151000000015 } ] }
requirement:
fetch document based on geolocation around 50km radius
what have tried:
db.getcollection('offers').aggregate([ { $geonear: { near: [6.0950994999999999, 49.8914114000000026], distancefield: "geolocation", maxdistance: 50000, //50 km radius } } ]);
problem:
it fetching documents instead of searching around 50km.
any suggestion grateful.
legacy coordinate pairs not return distances in meters, in radians instead. maxdistance therefore larger 50km. see calculate distances spherical geometry
but consider actual distance being used here:
db.getcollection('offers').aggregate([ { $geonear: { near: [6.0950994999999999, 49.8914114000000026], distancefield: "distance" } ]);
returns:
{ "_id" : objectid("55dc0f4b6f07ad5d3ec3b6d0"), "countrycode" : "de", "geolocation" : [ { "lat" : 50.8218537, "lng" : 9.020215100000001 } ], "distance" : 60.588259822017925 } { "_id" : objectid("55dc0f4b6f07ad5d3ec3b6cf"), "countrycode" : "lu", "geolocation" : [ { "lat" : 49.8914114, "lng" : 6.0950995 } ], "distance" : 61.93733827090219 }
as "distancefield" meant field reports projected distance queried point.
so start point documents ot valid geospatial queries. fix them this:
first drop indexes:
db.offers.dropindexes();
then fix fields:
var bulk = db.offers.initializeorderedbulkop(), count = 0; db.offers.find({}).foreach(function(doc) { //printjson(doc); var tmp = { "type": "point", "coordinates": [doc.geolocation[0].lng,doc.geolocation[0].lat] }; doc.geolocation = tmp; printjson(doc); bulk.find({ "_id": doc._id }).updateone({ "$set": { "geolocation": doc.geolocation } }); count++; if ( count % 1000 == 0 ) { bulk.execute(); bulk = db.offers.initializeorderedbulkop(); } });
now data represented in correct geojson format:
{ "_id" : objectid("55dc14856f07ad5d3ec3b6d1"), "countrycode" : "lu", "geolocation" : { "type" : "point", "coordinates" : [ 6.0950995, 49.8914114 ] } } { "_id" : objectid("55dc14856f07ad5d3ec3b6d2"), "countrycode" : "de", "geolocation" : { "type" : "point", "coordinates" : [ 9.020215100000001, 50.8218537 ] } }
now create index 2dsphere:
db.offers.createindex({ "geolocation": "2dsphere" })
now ready query:
db.offers.aggregate([ { "$geonear": { "near": { "type": "point", "coordinates": [6.0950994999999999, 49.8914114000000026] }, "distancefield": "distance", "spherical": true, "maxdistance": 50000 }} ])
which returns 1 document "near", or in fact 0 distance:
{ "_id" : objectid("55dc14856f07ad5d3ec3b6d1"), "countrycode" : "lu", "geolocation" : { "type" : "point", "coordinates" : [ 6.0950995, 49.8914114 ] }, "distance" : 0 }
Comments
Post a Comment