0

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

[
  {
    "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
}
4

1 回答 1

0

这可以使用聚合来实现。

[{
$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

于 2022-02-14T10:14:34.570 回答