问题
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