【问题标题】:Query MongoDb aggregate join two collections查询 MongoDb 聚合连接两个集合
【发布时间】:2023-03-28 19:34:02
【问题描述】:

我需要查询 mongoDb 的帮助

所以我有两个类似的集合

集合 A:

{someField: "123", anotherField: "456"},
{someField: "1234", anotherField: "4567"}

集合 B

{someField: "123", otherField: "789"}

带查询:

db.A.aggregate([
   {
      $lookup:
         {
           from: "B",
           let: { someField: "$someField", otherField: "$otherField" },
           pipeline: [
              { $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$someField",  "$$someField" ] },
                         { $eq: [ "$otherField",  "789" ] }                       
                       ]
                    }
                 }
              },
           ],
           as: "B"
         }
    }
])

我得到了所有集合 A,{someField: "1234", anotherField: "4567"} 中的 B 为空

我想要达到的效果是这样的:

{someField: "123", anotherField: "456", b: {someField: "123", otherField: "789"}}

提前谢谢你

【问题讨论】:

  • 如果B 数组大小大于零(参见$size),您可以在查找后过滤文档。
  • @prasad_ 怎么做?请指教
  • 请查看更新后的代码。

标签: mongodb mongodb-query


【解决方案1】:

你只需要在 let 部分声明$someField

db.collectionA.aggregate([
  {
    $lookup: {
      from: 'collectionB',
      let: { some_field: '$someField' },
      pipeline: [
        { $match: {
            $expr: {
              $and: [
                { $eq: [ "$someField", "$$some_field" ] },
                { $eq: [ "$otherField", "789" ] }
              ]
            }
          }
        }
      ],
      as: 'B'
    }
  },
  {
    $match: {
      $expr: {
        $gt: [ { $size: "$B" }, 0 ]
      }
    }
  }
])

https://mongoplayground.net/p/RTiUMWl8QaX

【讨论】:

  • 它仍然显示所有集合 A 而不仅仅是包含集合 B 的集合 A ...
  • @dImasAnggaSaputra 您可以反转查找或添加 $match 阶段。更新了我上面的答案。
【解决方案2】:

这就是我删除空的 B 数组文档的方法:

db.A.aggregate( [
   {
      $lookup: {
           from: "B",
           localField: "someField",
           foreignField: "someField",
           as: "B"
         }
    },
    {
       $addFields: {
            B: {
                 $filter: {
                      input: "$B",
                      cond: {
                          $eq: [ "$$this.otherField", "789" ]
                      }
                 }
            }
      }
    },
    {
       $match: { 
           $expr: {
                $gt: [ { $size: "$B" }, 0 ]
           }
       }
    }
] ).pretty()

【讨论】:

    猜你喜欢
    • 2020-01-10
    • 1970-01-01
    • 2016-09-27
    • 2014-02-23
    • 2017-07-13
    • 2020-09-19
    • 2019-10-13
    • 2020-06-13
    • 2012-05-11
    相关资源
    最近更新 更多