【发布时间】:2019-10-30 13:58:57
【问题描述】:
嘿 MongoDB 专家
我正在尝试使用 MongoDB 的各种位置功能($near、$geoNear 等)来实现一些查询结果。
我有这个 geoJSON 类型的猫鼬模型。
const geoSchema = new Schema({
type: {
type: String,
default: 'Point',
},
coordinates: {
type: [Number],
},
});
const pickupSchema = new Schema({
geo_location_from: geoSchema,
geo_location_to: geoSchema,
});
pickupSchema.index({ geo_location_from: '2dsphere' });
pickupSchema.index({ geo_location_to: '2dsphere' });
我想要达到的目标是靠近活动地点。
我有从 A 到 B 的主要接送事件,如图所示,我有所有位置的纬度和经度。现在我正在尝试从数据库中查询所有这些事件对象,其中事件 geo_location_from 靠近位置 A(例如:A1, A2, A3 )并且 geo_location_to 靠近位置 B( B1, B2 )。
这是我做的,这是不对的。我不是 100% 确定。
Pickup.find(
{
$and: [{
geo_location_from: {
$near: {
$maxDistance: 1000,
$geometry: {
type: 'Point',
coordinates: [args.longitude_from, args.latitude_from],
},
},
},
}, {
geo_location_to: {
$near: {
$maxDistance: 1000,
$geometry: {
type: 'Point',
coordinates: [args.longitude_to, args.latitude_to],
},
},
},
}],
},
)
我的一些尝试最终给出了各种错误。 比如geoNear 表达式太多等等。
对于这类问题,有人有什么好的解决方案吗?
【问题讨论】:
-
@philoez98 感谢您的回复。我看到了相关的帖子,但就我而言,我有 2 个不同的位置(从 ,到 ),我想找到这两个位置附近发生的所有其他位置。
-
您可以尝试将它们划分为不同的查询:第一个获得离 A 最近的地方,第二个获得离 B 最近的地方。然后您可以聚合它们并通过接近其中一个位置对结果进行排序.
-
@philoez98 感谢您精彩而快速的回复。您能否详细解释一下,我如何聚合它们并通过靠近其中一个位置对结果进行排序?
-
更多信息请参见下面的答案。