Reputation: 2020
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...
Upvotes: 2
Views: 99
Reputation: 46441
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"
}}
])
Upvotes: 2