node.js - 带有距离的Mongodb过滤器不起作用
问题描述
我正在尝试过滤最大距离为 10 公里的经纬度。这是我的nodejs mongodb代码实现:
dbo.collection('CT').createIndex( { "loc" : "2dsphere" } );
var findquery = {
"GeoJSON.loc": {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ 103.819839, 1.352083], //Long Lat
$maxDistance:10000
}
}
}
};
dbo.collection("CT").find(findquery).toArray(function(err, result) {
console.log(result);
db.close();
});
数据存储如下 mongodb:
[ {
"_id": "5bc04226df7ea7503c7d57f1",
"results": [
{
"ID": "FD02328677"
}
],
"GeoJSON": [
{
"city": "Los Angeles",
"loc": {
"type": "Point",
"coordinates": [
-118.24532,
34.05349
]
}
},
{
"city": "Tampa",
"loc": {
"type": "Point",
"coordinates": [
-82.45927,
27.94653
]
}
},
{
"city": "Seattle",
"loc": {
"type": "Point",
"coordinates": [
-122.32945,
47.60358
]
}
}
] } ]
当我运行代码时,我可以获得结果(我不应该这样做),看起来过滤器功能不适用于我的代码。有什么建议吗?
解决方案
只是几个错别字:
指数
dbo.collection('CT').createIndex( { "loc" : "2dsphere" } );
应该
dbo.collection('CT').createIndex( { "GeoJSON.loc" : "2dsphere" } );
否则,运行查询时会出错。
查询
var findquery = {
"GeoJSON.loc": {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ 103.819839, 1.352083], //Long Lat
$maxDistance:10000
}
}
}
};
应该
var findquery = {
"GeoJSON.loc": {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ 103.819839, 1.352083], //Long Lat
},
$maxDistance:10000
}
}
};
在您的查询中,$maxDistance
内部$geometry
被忽略。没有$maxDistance
in$near
所以返回所有记录。
推荐阅读
- javascript - 如何覆盖 javascript 表单小部件的属性
- haskell - 类型类函数的显式 forall
- mysql - 返回最受欢迎的预订日
- stenciljs - Stencil JSX 监听器抛出异常
- python - 无法使用 Pycharm 安装任何东西,因为管道没有 pip-egg-info(19.0.2)
- html - 使滚动粘性元素的优先级高于更改元素位置
- javascript - 将具有相同键的数组元素加在一起?
- javascript - 如何使用javascript使图像在悬停时移动?
- php - Apache2 / Debian 9 上的写入权限被拒绝
- crystal-reports - 需要比较一张表中两列的值