简体   繁体   中英

Query MongoDb aggregate join two collections

I need help for querying mongoDb

So I have two collections like

Collection A:

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

Collection B

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

with Query:

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

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

What I want to achieve is like:

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

Thank you in advance

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

This is how I removed the empty B array documents:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM