how to use geoNear in nodejs?

不羁的心 提交于 2020-01-01 14:09:11

问题


I want to use geospatial geoNear, database in mongodb, Mongo Query:

db.runCommand(
   {
     geoNear: "tmp",
     near: { type: "Point", coordinates: [ 77.00000, 12.00000] },
     spherical: true,
     maxDistance : 200
   }
)

Gives result in mongo terminal, but how to execute it using node.js I am using mongo-pool and generic-pool for mongo pooling?


回答1:


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);       
    });      
});


来源:https://stackoverflow.com/questions/29255525/how-to-use-geonear-in-nodejs

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