Usa $geoNear
operatore per la pipeline di aggregazione (disponibile se si utilizza MongoDB 2.4 o versioni successive). Ad esempio:
var mongodb = require('mongodb')
, MongoClient = mongodb.MongoClient
, express = require('express')
, app = express();
var db;
MongoClient.connect(process.env.MONGOHQ_URL, function(err, database) {
db = database;
app.listen(1337);
});
app.get('/geospatial', function(req, res) {
db.collection('collection_name').aggregate([
{
"$geoNear": {
"near": {
"type": "Point",
"coordinates": [parseFloat(req.params.lng), parseFloat(req.params.lat)]
},
"distanceField": "distance",
"maxDistance": 200,
"spherical": true,
"query": { "loc.type": "Point" }
}
},
{
"$sort": {"distance": -1} // Sort the nearest first
}
],
function(err, docs) {
res.json(docs);
});
});