【问题标题】:Lookup based on match result根据匹配结果查找
【发布时间】:2022-01-30 10:36:56
【问题描述】:

我有集合名称服务:

[
    {
        "_id": "61dad1d21aa077c61b7bc2aa",
        "name": "HomeMaintenance",
        "subServices": [
            "61dacb86cb94917c1edcea8f",
            "61dad5812881410ba441c401"
        ],
    },
    {
        "_id": "61dad60b2881410ba441c40e",
        "name": "HomeMaintenance",
        "subServices": [],
    }
]

另一方面,我有一个这样的子服务集合:

[
    {
        "_id": "61dacb86cb94917c1edcea8f",
        "name": "something",
        "title": "something else",
        "imageUrl": "",
        "__v": 0,
        "service": "61dad1d21aa077c61b7bc2aa"
    },
    {
        "_id": "61dad5812881410ba441c401",
        "name": "Plumbing",
        "title": "Plumbing",
        "imageUrl": "",
        "__v": 0,
        "service": "61dad1d21aa077c61b7bc2aa"
    }
]

我想出了一个包含两个这样的查询的解决方案

const requestedService = (serviceId)=>{
  return servicesModel.findById(id);
};


const ids= requestedService.subServices

const subServicesList = (ids) => {
  return subServicesModel.find({
    _id: {
      $in: ids,
    },
  });
};

效果很好,我想知道有没有办法用一个带有查找阶段的聚合管道来执行这些查询,首先从服务集合中找到主要服务,然后从子服务集合中找到服务的子服务 像这样的

const result = await servicesModel.aggregate([
    {
      $match: { _id: ObjectId(id) },
    },

    {
      $lookup: {
        from: "sub_services",
        let: { pid: "$_id" },

        pipeline: [
          {
            $match: {
              $expr: {
                $in: ["$$pid" //>>  id in sub_services modal , //>> "array which we get from match" ],
              },
            },
          },
        ],

        as: "subServices",
      },
    },

]);

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    let 用于声明 left 文档中的变量。

    指定要在管道阶段中使用的变量。使用变量表达式访问输入到管道的连接集合文档中的字段。

    db.services.aggregate([
      {
        $match: {
          _id: ObjectId(id)
        },
      },
      {
        $lookup: {
          from: "sub_services",
          let: {
            subServices: "$subServices"
          },
          pipeline: [
            {
              $match: {
                $expr: {
                  $in: [
                    "$_id",
                    "$$subServices"
                  ]
                },
                
              },
              
            },   
          ],
          as: "subServices",  
        }, 
      }, 
    ])
    

    Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多