如何在nodejs中使用geoNear? [英] how to use geoNear in nodejs?
本文介绍了如何在nodejs中使用geoNear?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要使用地理空间geoNear,mongodb中的数据库,mongo查询:
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
}
)
给定结果导致mongo终端,但是如何使用node.js执行它,我在mongo池中使用mongo-pool和generic-pool?
Gives result in mongo terminal, but how to execute it using node.js I am using mongo-pool and generic-pool for mongo pooling?
推荐答案
使用 $geoNear
用于聚合管道的操作符(如果您使用的是MongoDB 2.4或更高版本,则可用).例如:
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);
});
});
这篇关于如何在nodejs中使用geoNear?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文