最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

$lookup 之前的 $geoNear 是性能问题吗?

网站源码admin30浏览0评论

$lookup 之前的 $geoNear 是性能问题吗?

$lookup 之前的 $geoNear 是性能问题吗?

我有两项资产。一大一小。 我把小的和大的联系起来。 我有大的地理定位数据。 我想将聚合管道用于 $match 地理位置数据。但聚合在第一阶段需要 $geoNear。 我想知道在大查询上应用查询是否会影响性能。 如果是这样,我如何在第一步要求绕过 $geoNear 的同时将查询应用于小查询?

我搜索了所有互联网以找到解决方案我没有找到解决方案。

回答如下:

在大型数据集上使用

$geoNear
可能会很慢,尤其是在没有地理空间索引的情况下。为了优化性能,请确保您在包含大集合中的地理位置数据的字段上有一个地理空间索引。

要在较小的集合上执行查询,同时仍然使用来自大集合的地理位置数据,您可以使用聚合管道中的

$lookup
阶段来连接两个集合。

这是一个演示这种方法的示例管道:

    db.small_collection.aggregate([
  {
    $lookup: {
      from: "big_collection",
      localField: "big_collection_id", // The field in the small collection that relates to the big collection
      foreignField: "_id", // The field in the big collection to match against
      as: "big_collection_data" // The array to store the matched big collection data
    }
  },
  {
    $unwind: "$big_collection_data" // Flatten the array for easier processing
  },
  {
    $match: {
      "big_collection_data.geolocation": {
        $nearSphere: {
          $geometry: {
            type: "Point",
            coordinates: [<longitude>, <latitude>]
          },
          $maxDistance: <maxDistanceInMeters>
        }
      }
    }
  },
  // Add any additional stages as needed
]);

这条管道首先执行一个

$lookup
,根据它们的关系加入小集合和大集合。然后,它展开
big_collection_data
数组,最后使用
$match
阶段和来自大集合的地理定位数据过滤结果。

但是,请记住,如果与大集合相关的字段上没有索引,则此方法仍然必须对小集合执行完整集合扫描。为了提高性能,也可以考虑在小型集合中的该字段上添加索引。

发布评论

评论列表(0)

  1. 暂无评论