MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

wie verwendet man geoNear in nodejs?

Verwenden Sie $geoNear -Operator für die Aggregationspipeline (verfügbar, wenn Sie MongoDB 2.4 oder höher verwenden). Zum Beispiel:

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