【问题标题】:Have a Question about Mongodb Aggregate if nested如果嵌套,对 Mongodb Aggregate 有疑问
【发布时间】:2021-09-29 07:48:23
【问题描述】:

我正在使用 aggregate 创建一个函数。我正在使用查找来绑定三个数据库。下面的函数组成时,有没有办法绑定A的数据和C的数据?

A.aggregate([
    {
      $lookup: {
        from: "B",
        let: { aid: "$aid" },
        pipeline: [
          { $match: { $expr: { $in: ["$_id", "$$aid"] } } },
          {
            $lookup: {
              from: "C",
              let: { bid: "$bid" },
              pipeline: [
                {
                  $match: {
                    $expr: {
                      $eq: ["$$bid, "$aid"],
                    },
                  },
                },
              ],
              as: "list",
            },
          },
        ...
  ])

【问题讨论】:

  • 您能否详细说明“捆绑”和“绑定”是什么意思?从您的示例中,您应该已经能够从 A 中查找 C 中的数据
  • 我想知道是否有可能在C的管道中找到与A的字段匹配的值。
  • 从 A 查找 C 和从 C 查找 A 有什么区别吗?您可能想给我们一些示例数据和预期输出,以向我们展示您想要实现的目标。 Mongo playground 将是有用的工具之一。

标签: node.js mongodb mongoose aggregate lookup


【解决方案1】:

我对此进行了更多了解,并且通过执行以下操作找到了我正在寻找的结果:

A.aggregate([
    {
      $lookup: {
        from: "B",
        let: { bid: "$bid", aid: "$aid" },
        pipeline: [
          { $match: { $expr: { $in: ["$_id", "$$bid"] } } },
          {
            $lookup: {
              from: "C",
              localField: "_id",
              foreignField: "cid",
              as: "list",
            },
          },
          {
            $unwind: "$list",
          },
          // One More Match
          {
            $match: { $expr: { $eq: ["$$aid", "$list.aid"] } },
          },
          {
            $addFields: {
              list: "$list.clist",
            },
          },
        ],
        as: "blist",
      },
    },
  ])

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    相关资源
    最近更新 更多