如何在nodejs中使用geoNear?

时间:2015-03-25 12:21:30

标签: node.js mongodb geospatial

我想在mongodb中使用geospatial geoNear,数据库,Mongo查询:

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

给mongo终端带来结果,但是如何使用node.js执行它我使用mongo-pool和generic-pool进行mongo池化?

1 个答案:

答案 0 :(得分:3)

使用$geoNear运算符作为聚合管道(如果您使用的是MongoDB 2.4或更高版本,则可用)。例如:

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