我有一个集合“产品”,另一个集合“交易”,然后是“用户”。每种产品都有一些交易,每笔交易都有一个用户。所以我想获取产品......
我有一个集合“产品”、另一个集合“交易”以及“用户”。每种产品都有一些交易,而每笔交易都有一个用户。因此,我想从用户集合中获取具有交易键值对的产品,其中包含基于产品 ID 的数组,然后每个交易都包含基于旅行者 ID 的旅行者键值对。
如果存在一些交易,则我已实现所需的输出,但如果没有交易,则它不会返回交易:[],而是返回交易:[{}]
我正在运行这个查询:
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();
我的输出是:
[
{
"_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": [
{}
]
}
]