I have a collection “products”, another “transactions” and then “users”.
Every product has some transactions and every transaction has a user.
So I want to fetch products having a key-value pair of transactions containing an array based on productId
And then every transaction containing a key-value pair of traveller based on travellerId from users collection.
I have achieved the desired output if there are some transactions but if transacitons are not there. Then instead of having transactions: [], it sends me back transactions: [{}]
I am running this query:
const tripProducts = await db.collection('products')
.aggregate([
{ $match: { tripId: new ObjectId(tripId ?? '') } },
{ $lookup: { from: 'transactions', localField: '_id', foreignField: 'productId', as: 'transactions' } },
{ $unwind: { path: '$transactions', preserveNullAndEmptyArrays: true } }, // Unwind transactions array
{ $lookup: { from: 'users', localField: 'transactions.travellerId', foreignField: '_id', as: 'traveller' } },
{ $unwind: { path: '$traveller', preserveNullAndEmptyArrays: true } }, // Unwind traveller array
{ $addFields: { 'transactions.traveller': '$traveller' } },
{
$group: {
_id: '$_id',
// Include all fields from products using $first or similar operators
tripId: { $first: '$tripId' },
name: { $first: '$name' },
category: { $first: '$category' },
productPrice: { $first: '$productPrice' },
currency: { $first: '$currency' },
depositForBusiness: { $first: '$depositForBusiness' },
depositDate: { $first: '$depositDate' },
finalDate: { $first: '$finalDate' },
minTravellers: { $first: '$minTravellers' },
maxTravellers: { $first: '$maxTravellers' },
amount: { $first: '$amount' },
depositAmount: { $first: '$depositAmount' },
platformFeeForDeposit: { $first: '$platformFeeForDeposit' },
platformFee: { $first: '$platformFee' },
userId: { $first: '$userId' },
transactions: { $push: '$transactions' } // Push the transactions with the traveller details
}
}
])
.toArray();
And my output is:
[
{
"_id": "66d62cb0caeb8c9e204a10b5",
"tripId": "66d62bc5caeb8c9e204a10b3",
"name": "Next Year",
"category": "🏨 Stay",
"productPrice": 10000,
"currency": "usd",
"depositForBusiness": 1000,
"depositDate": "2024-09-04T19:00:00.000Z",
"finalDate": "2025-04-09T19:00:00.000Z",
"minTravellers": 1,
"maxTravellers": 2,
"amount": 10975.6,
"depositAmount": 1098.1,
"platformFeeForDeposit": 98.1,
"platformFee": 975.6000000000004,
"userId": "66bb9220366e6c4942f4943e",
"transactions": [
{}
]
},
{
"_id": "66d73682b976159272117780",
"tripId": "66d62bc5caeb8c9e204a10b3",
"name": "Tomorrow",
"category": "🏨 Stay",
"productPrice": 1000,
"currency": "dkk",
"depositForBusiness": 100,
"depositDate": "2024-09-03T19:00:00.000Z",
"finalDate": "2024-09-03T19:00:00.000Z",
"minTravellers": 1,
"maxTravellers": 2,
"amount": 1098.1,
"depositAmount": 110.35,
"platformFeeForDeposit": 10.35,
"platformFee": 98.09999999999991,
"userId": "66bb9220366e6c4942f4943e",
"transactions": [
{}
]
}
]