我正在我的'用户'集合上运行一个聚合,以分配一个在用户坐标半径范围内的城市列表.

似乎没有办法将let变量分配给maxDistance字段,因为这只能接受原始数字.

有没有其他方法可以不用$geoNear$geoWithin来做同样的计算,因为这两种方法都有相同的限制.

$lookup: {
  from: 'cities'
  let: {
    userCoordinates: '$coordinates',
    userSearchRadius: '$searchRadius'
  },
  pipeline: [
    {
      $geoNear: {
        near: {
          type: "Point",
          coordinates: '$$userCoordinates'
        },
        distanceField: 'distance',
        maxDistance: '$$userSearchRadius', // Issue here
        spherical: true,
      }
    }
  ],
  as: 'nearbyCities'
}

推荐答案

解决问题的一个解决办法是在计算的distance字段的$geoNear阶段之后添加一个$match阶段.

db.users.aggregate([
  {
    $lookup: {
      from: "cities",
      let: {
        "userCoordinate": "$coordinate",
        "userSearchRadius": "$searchRadius"
      },
      as: "nearByCities",
      pipeline: [
        {
          $geoNear: {
            near: "$$userCoordinate",
            spherical: true,
            distanceField: "distance"
          }
        },
        {
          "$match": {
            $expr: {
              $lte: [
                "$distance",
                "$$userSearchRadius"
              ]
            }
          }
        }
      ]
    }
  },
  {
    $unwind: {
      path: "$nearByCities",
      preserveNullAndEmptyArrays: true
    }
  }
])

Mongo Playground

Mongodb相关问答推荐

MongoDB:从集合页面数据中提取不同的值

如何将空值单独分组?

所有文档中嵌套 struct 中的条件匹配-mongodb

从MongoDB迁移到PostgreSQL:为PostgreSQL编写聚合管道查询

Mongoose 聚合和多级组

mongoDB文档数组字段中的唯一项如何

Mongoose - $project 嵌套的对象数组到数组的根级别

增加嵌套对象中的值?

Mongoid 有 Map/Reduce 吗?

python mongodb正则表达式:忽略大小写

.NET 中的 Mongodb 单元测试

MongoDB聚合排序不起作用

NoSQL:MongoDB 或 BigTable 并不总是 Available意味着什么

MongoDB - 文件大小巨大且不断增长

Python Django-REST-framework 和 Angularjs 的文件夹 struct

MongoException: Index with name: code already exists with different options

MongoDB 在 mongoengine 中使用 OR 子句

Mongodb 设计,嵌入与关系

MongoDB 的 MMAPV1、WiredTiger 或 In-Memory StorageEngine 如何 Select ?

在 NodeJs 中处理 Mongodb 全局连接的最佳方法是什么