首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mongodb _

使用mongodb _
EN

Stack Overflow用户
提问于 2019-06-16 23:53:24
回答 1查看 5.8K关注 0票数 0

嘿,MongoDB专家

我试图使用MongoDB的各种位置特性($near、$geoNear等)来实现一些查询结果。

我有geoJSON型的猫鼬模型。

代码语言:javascript
复制
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的主要拾取活动,如图像所示,我有所有位置的纬度和经度。现在,我试图从db查询所有这些事件对象,其中事件geo_location_from按位置A(例如: A1、A2、A3 )和位置B( B1、B2 )接近。

我做了一件事,这是不对的。我不是百分之百肯定。

代码语言:javascript
复制
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表达式太多了,等等。

有谁能很好地解决这种问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-17 18:01:48

因此,我一直在考虑一种聪明的方法来完成您所要求的一切,但我认为仅用MongoDb很难(如果不是不可能的话)做到这一点。一个完美的解决方案是使用https://turfjs.org/和MongoDb。

我想出了一种可能是你想要的方法。

为了使所有同时靠近两个空间点的地方,我们需要定义一个多边形(一个区域)来寻找这些地方。考虑到大多数情况下,你只有两个点,多边形必须类似于一个圆。

没有办法用GeoJson来做这件事,所以turf.js进来了。你可以这样做:

代码语言:javascript
复制
// 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.js和MongoDb文档,以便更清楚地了解如何使它们无缝地协同工作(并可能找到比我的更好、更容易的解决方案)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56623437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档