【发布时间】:2020-08-21 21:57:41
【问题描述】:
我正在尝试总结查找中列出的值。我有 2 个收藏:
订阅(伪代码)
{
_id,
purchaseDate: Date,
wholesalePrice: Number,
purchasePrice: Number,
retailPrice: Number,
userID: String,
}
付款
{
_id,
statementMonth: String, // e.g. 2020-08 (same as grouped id in Subscriptions)
paymentDate: Date,
userID: String,
amountPaid
}
用户需要在月底转移利润率值。因此,我想为 Statements 创建一个输出。这些将所有订阅和付款分组到每月记录中,其中包含所有数据的摘要。我已经设法创建了第一组的所有内容,但是一旦我进行查找以获取付款详细信息,一切似乎都失败了。
这是我目前的管道
{
"$match": {
"userID": [provided UserID]
}
},
{
"$group": {
"_id": {
"$dateToString": {
"format": "%Y-%m",
"date": "$purchaseDate"
}
},
"totalWholesalePrice": {
"$sum": "$wholesalePrice"
},
"totalPurchasePrice": {
"$sum": "$purchasePrice"
},
"count": {
"$sum": 1.0
}
}
},
{
"$addFields": {
"totalAmountDue": {
"$subtract": [
"$totalPurchasePrice",
"$totalWholesalePrice"
]
}
}
},
{
"$lookup": {
"from": "transactions",
"localField": "_id",
"foreignField": "statementMonth",
"as": "transactions"
}
},
{
"$unwind": {
"path": "$transactions",
"preserveNullAndEmptyArrays": true
}
},
{
"$sort": {
"_id": -1.0
}
}
如果有 2 笔交易,则返回 2 条记录:
{
"_id" : "2020-08",
"totalWholesalePrice" : NumberInt(89),
"totalPurchasePrice" : 135.55,
"count" : 8.0,
"totalAmountDue" : 46.55,
"transactions" : {
"_id" : ObjectId("5f3faf2216d7a517bc51bfae"),
"date" : ISODate("2020-04-20T11:23:40.284+0000"),
"statementMonth" : "2020-08",
"merchant" : "M1268360",
"amountPaid" : "40"
}
}
{
"_id" : "2020-08",
"totalWholesalePrice" : NumberInt(89),
"totalPurchasePrice" : 135.55,
"count" : 8.0,
"totalAmountDue" : 46.55,
"transactions" : {
"_id" : ObjectId("5f3fc13f16d7a517bc51c047"),
"date" : ISODate("2020-04-20T11:23:40.284+0000"),
"statementMonth" : "2020-08",
"merchant" : "M1268360",
"amountPaid" : "2"
}
}
我希望最终的 JSON 是:
{
"_id" : "2020-08",
"totalWholesalePrice" : NumberInt(89),
"totalPurchasePrice" : 135.55,
"count" : 8.0,
"totalAmountDue" : 46.55,
"transactions" : [{
"_id" : ObjectId("5f3faf2216d7a517bc51bfae"),
"date" : ISODate("2020-04-20T11:23:40.284+0000"),
"statementMonth" : "2020-08",
"merchant" : "M1268360",
"amountPaid" : "40"
}
{
"_id" : ObjectId("5f3fc13f16d7a517bc51c047"),
"date" : ISODate("2020-04-20T11:23:40.284+0000"),
"statementMonth" : "2020-08",
"merchant" : "M1268360",
"amountPaid" : "2"
}],
"totalPaid" : 42,
"totalBalance" : 4.55,
}
【问题讨论】: