MongoDB $geoNear 聚合另一个集合

问题描述 投票:0回答:1

我有一个包含两个集合的数据库,如下所示:

[
  {
    "name": "Person A",
    "location": {"type": "Point", "coordinates": [180, 90]}
  },
  {
    "name": "Person B",
    "location": {"type": "Point", "coordinates": [-180, -90]}
  }
]
[
  {
    "name": "Store A",
    "location": {"type": "Point", "coordinates": [180, 90]}
  },
  {
    "name": "Store B",
    "location": {"type": "Point", "coordinates": [-180, -90]}
  }
]

对于每个人,我想找到最近的地方。我可以让它找到一对特定坐标的最近位置,而不是整个集合。有什么方法可以在不使用

foreach
的情况下做到这一点吗? 这是我按照 MongoDB 文档得到的最接近的结果:

// Current $geoNear:
{
  // Instead of having to give constants of a single
  // point, I want to compare against all coordinates
  // of another collection.              ↓
  near: {"type":"Point","coordinates":[-180, 90]},
  distanceField: 'distance',
  maxDistance: 50,
  spherical: true
}
mongodb aggregation-framework mongodb-geospatial
1个回答
1
投票

这可以通过聚合来实现。

[{
$lookup: {
  from: "places",
  let: {
    "personPoint": "$location"
  },
  as: "nearestPlace",
  pipeline: [
    {
      $geoNear: {
        near: "$$personPoint",
        spherical: true,
        distanceField: "distance",
        maxDistance: 50,
        
      }
    },
    {
      $unwind: "$location"
    },
    
  ]
 }
},
{
 $unwind: {
  path: "$nearestPlace",
  preserveNullAndEmptyArrays: true
 }
}]

由于地理索引,我无法在操场上测试它。所以可能需要一些小修复。如果有人可以让它在操场上工作,请点击链接 https://mongoplayground.net/p/aROX976gYzC


编辑:这是一个具有 2dsphere 索引的 Playground 链接
游乐场

© www.soinside.com 2019 - 2024. All rights reserved.