我有一個事務模型,其中有事務的描述和狀態字段。像下面如何在使用聚合和組時使用其他對象字段
[
{
"_id": "5795e3f4f4a0fb8c1dff20ad",
"description": "This is a transcation",
"invoice_id": "5795db00bfa9d366194a454d",
"amount": 50
},
{
"_id": "5795e3faf4a0fb8c1dff20ae",
"description": "This is a transcation",
"invoice_id": "5795db00bfa9d366194a454d",
"amount": 100
}
]
我使用的聚集和分組這些記錄找到匹配對象的totalAmount
。因此,對於這個目的,我使用這個查詢:
Transaction.aggregate([{
$match: {
invoice: ObjectId("5795db00bfa9d366194a454d")
}
}, {
$group: {
_id: {
_id: "$_id"
},
count: {
$sum: 1
},
totalAmount: {
$sum: "$amount"
},
}
}
])
當我運行它,我得到以下結果
/* 1 */
{
"_id": {
"_id": ObjectId("5796031e07bad1d21f3af823")
},
"count": 1.0,
"totalAmount": 100
}
/* 2 */
{
"_id": {
"_id": ObjectId("5795e3f4f4a0fb8c1dff20ad")
},
"count": 1.0,
"totalAmount": 50
}
,但我想所有這一切連同具有特定invoice_id
的匹配對象totalAMount
和其他字段如description
。應該是這樣的
[{
"_id": {
"_id": ObjectId("5795e3f4f4a0fb8c1dff20ad")
},
"description": "description of first object",
"count": 5.0,
"totalAmount": 350
}, {
"_id": {
"_id": ObjectId("5795e3f4f4a0fb8c1dff20ad")
},
"description": "description of second object",
"count": 5.0,
"totalAmount": 350
}]
我該如何實現這個解決方案?
你怎麼能組由$ _id因爲它對每個文件都是唯一的? – Webdev
@Bhawana你問我?這是作者的代碼,他說它在他的情況下按預期工作。我不是他的老闆,他說這個代碼沒有意義。 –
你的回答是有幫助的,但請看看我期望的結果,我提到的問題。 我需要每個匹配對象的TotalAmount。 例如,如果有兩個匹配對象,每個對象的數量分別爲50 100,那麼每個匹配對象將顯示totalAmount = 150 –