【问题标题】:Find objects of near locations using mongodb | all nearby location A to all nearby location B使用 mongodb 查找附近位置的对象 |所有附近的位置 A 到所有附近的位置 B
【发布时间】: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 感谢您精彩而快速的回复。您能否详细解释一下,我如何聚合它们并通过靠近其中一个位置对结果进行排序?
  • 更多信息请参见下面的答案。

标签: mongodb mongoose geojson


【解决方案1】:

所以我一直在想一个聪明的方法来完成你所要求的一切,但我认为仅使用 MongoDb 很难(如果不是不可能)做到这一点。 一个完美的解决方案是恕我直言,将 turf.js 与 MongoDb 一起使用。
我想出了一种方法,我认为这可能是您正在寻找的方法。

为了让所有同时靠近两个空间点的地方,我们需要定义一个多边形(一个区域)来寻找这些地方。鉴于大多数时候您只有 2 个点,因此多边形必须类似于圆形。

GeoJson 没有办法做到这一点,所以 turf.js 进来了。你可以这样做:

// create the points
let point1 =  turf.point([-90.548630, 14.616599]);
let point2 = turf.point([-88.548630, 14.616599])

// we get the midpoint that we'll use as the center of our circle
const midPoint = turf.midpoint(point1, point2) 

// we create a polygon that we'll use as our area
const options = {steps: 100, units: 'kilometers'}; // options for the circle
const circle = turf.circle(midPoint, options)

// a possible place near both locations
let point3 = turf.point([-91.43897, 14.56784])

// then you can get if a point is inside the circle or not
const inside = turf.booleanWithin(point3, circle) 

这只是一个想法。您可以自定义圆圈的半径以获得更远或更近的地方。然后你当然可以通过靠近中心来订购你在圆圈内找到的地方(这可以在 MongoDb 中轻松完成)。

我建议您仔细查看 turf.jsMongoDb 文档,以便更清楚地了解如何使它们无缝协作(也许找到比我更好、更简单的解决方案)。

【讨论】:

  • 感谢您的精彩回答@philoez。我一定会看看这个。
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多