【问题标题】:Mongoose - $in doesn't respect orderMongoose - $in 不尊重顺序
【发布时间】:2022-01-21 18:45:20
【问题描述】:

我将 NestJS 与 Mongoose 一起使用,我有 2 个集合、区域和诊所

首先我搜索用户附近的地区

async findAllByLocation(location: Location) {
    const territories = await this.territoryModel.find({
      location: {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [location.lat, location.long],
          },
        },
      },
    });
    return territories.map((territory) => {
      return {
        _id: territory._id,
        name: territory.name,
      };
    });
  }

然后诊所服务利用此函数从返回的数组中获取具有任何区域的诊所

  async getClinicsByLocation(location: any): Promise<any> {
    const territories = await this.territoryService.findAllByLocation(location);
    const clinics = await this.clinicModel.find({
      territory: { $in: territories.map((t) => t._id) },
    });
    return clinics;
  }

我现在的问题是区域数组是从最近到最远排序的,但是诊所是随机顺序的,因此诊所在响应中的领土比其他诊所更远

一种解决方案是在每个区域单独建立诊所,然后合并阵列,但这既不节省时间,也不节省性能

有什么想法吗?

【问题讨论】:

    标签: typescript mongodb mongoose


    【解决方案1】:

    我认为您可以在一个聚合查询中做到这一点。输入和输出示例也会有所帮助。

    顺便说一句,对于您的查询,我认为您想要:

    1. 获取某个位置附近的所有地区
    2. 仅返回 _idname
    3. 搜索territory 字段与territories 中的_id 相同的诊所。

    所以我认为这可以在一个这样的查询中完成:

    db.territories.aggregate([
      {
        $geoNear: {
          near: {
            type: "Point",
            coordinates: [location.lat, location.long]
          },
          distanceField: "dist.calculated"
        }
      },
      {
        $project: {
          name: 1
        }
      },
      {
        $lookup: {
          from: "clinics",
          localField: "_id",
          foreignField: "territory",
          as: "clinics"
        }
      },
      {
        $unwind: "$clinics" // optional; it depends the output you want
      }
    ])
    

    结果是这样的:

    {
       "_id":2,
       "name":"territory name 2",
       "clinics":{
          "_id":ObjectId("61ea8a20f90aaa6f3e23efac"),
          "territory":2,
          "name":"clinic2"
       }
    }{
       "_id":1,
       "name":"territory name 1",
       "clinics":{
          "_id":ObjectId("61ea8a20f90aaa6f3e23efab"),
          "territory":1,
          "name":"clinic1"
       }
    }{
       "_id":3,
       "name":"territory name 3",
       "clinics":{
          "_id":ObjectId("61ea8a20f90aaa6f3e23efad"),
          "territory":3,
          "name":"clinic3"
       }
    }
    

    我使用mongo $geoNear example 作为输入数据,并且在所有执行中顺序都是相同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      相关资源
      最近更新 更多