查询MongoDb聚合联接两个集合 [英] Query MongoDb aggregate join two collections

查看:685
本文介绍了查询MongoDb聚合联接两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要查询mongoDb的帮助

I need help for querying mongoDb

所以我有两个类似的收藏

So I have two collections like

收藏集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"}

I get all collection A, with B empty in {someField: "1234", anotherField: "4567"}

我想要实现的目标是:

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

提前谢谢

推荐答案

您只需要在let部分声明$someField.

you only need to declare $someField in the let section.

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

这篇关于查询MongoDb聚合联接两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆