how to use geoNear in nodejs?

邮差的信 提交于 2019-12-04 10:08:40

Use the $geoNear operator for the aggregation pipeline (available if you are using MongoDB 2.4 or greater). For example:

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