Gebruik de $geoNear
operator voor de aggregatiepijplijn (beschikbaar als u MongoDB 2.4 of hoger gebruikt). Bijvoorbeeld:
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);
});
});