首页 > 解决方案 > 查询 MongoDb 聚合连接两个集合

问题描述

我需要查询 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,其中 B 为空{someField: "1234", anotherField: "4567"}

我想要实现的是:

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

先感谢您

标签: mongodbmongodb-query

解决方案


这就是我删除空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()

推荐阅读