简体   繁体   中英

Getting subdocuments using $lookup

I want to get the subdocuments from another collection using $lookup but it doesn't work. Currently brain dead...

I have a collection for Transactions

example transaction

{
  type: 'PURCHASE',  // but it can be something else also eg ORDER
  reference: '11', // String
  amount: 50,
  date: 2018-07-18T10:00:00.000Z
}

I have a collection for Purchases

{
  code: 11 // Integer
  name: 'Product X',
  amount: 50
}

My aggregation is the following

Purchase.aggregate([ 
        {
            $lookup:
              {
                from: "transactions",   
                let: { code: '$code' },
                pipeline: [ 
                    {

                    },
                    { 
                        $match: { $expr:
                            { $and:
                               [
                                 { $eq: [ "$reference",  "$$code" ] },
                                 { $eq: [ "$type", "PURCHASE" ] }
                               ]
                            }
                         }

                    }
                ], 
                as: "transactions",

              }
         }
 ]);

The result is an empty tarnsactions array...

You can try below aggregation in mongodb 3.6 . Just change code type from integer to string using $toLower aggregation or can use $toString in mongodb 4.0

Purchase.aggregate([ 
  { "$lookup": {
    "from": "transactions",   
    "let": { "code": { "$toLower": "$code" } },
    "pipeline": [ 
      { "$match": {
        "$expr": { "$eq": [ "$reference",  "$$code" ] },
        "type": "PURCHASE"
      }}
    ],
    "as": "transactions"
  }}
])

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