查询MongoDb聚合联接两个集合

时间:2020-03-02 11:01:53

标签: mongodb mongodb-query

我需要查询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"}}

提前谢谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这是我删除空的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()
相关问题