[英]MongoDB Aggregation - Sum value of nested arrays
我試圖獲取數組內的特定字段的總和。 問題是,該數組也位於另一個數組中。 我的文檔如下(簡體):
{
"nome": "test-1"
"notas": [{
"numero_fiscal": "0001",
"valores": {
"portal": 1000,
"arquivo": 1000
},
"abatimentos": [{
"valor": 250,
"tipo": "TIPO 1"
}, {
"valor": 250,
"tipo": "TIPO 2"
}]
}, {
"numero_fiscal": "0002",
"valores": {
"portal": 2000,
"arquivo": 2000
},
"abatimentos": [{
"valor": 500,
"tipo": "TIPO 1"
}, {
"valor": 500,
"tipo": "TIPO 2"
}]
}]
}
我希望我的輸出是這樣的:
{
"_id": "resumo",
"total_notas": 2, // this is the counter for the array "notas"
"soma_portal": 3000, // this is the sum of the "valores.portal" of all "notas"
"soma_arquivo": 3000, // this is the sum of the "valores.arquivo" of all "notas"
"soma_abatimento": 1500 // this is the sum of all the "abatimentos.valor" from all the "notas"
}
我嘗試了以下聚合(以及其他聚合,但結果始終相同):
Notas.aggregate()
.match(my_query)
.unwind('notas') // unwinding 'notas' array
.group({
'_id': 'resumo',
'total_notas': { '$sum': 1 },
'abatimentos': { '$push': '$notas.abatimentos' },
'soma_portal': { '$sum': { '$notas.valores.portal' } },
'soma_arquivo': { '$sum': { '$notas.valores.arquivo' } }
})
.unwind('$abatimentos')
.group({
'_id': '$_id',
'total_notas': { '$first': '$total_notas' },
'soma_portal': { '$first': '$soma_portal' },
'soma_arquivo': { '$first': '$soma_arquivo' },
'soma_abatimento': { '$sum': '$abatimentos.valor' }
})
這給了我幾乎所有我想要的正確信息,但是'soma_abatimento'始終為0,而不是1500
我在正確的道路上嗎? 還是在數據庫查詢中不應該這樣做?
在當前版本中,您需要添加雙精度$ unwind,因為您已經正確地確定了,在第一個$ group之后,數組中有一個數組。
這是一個稍作修改的版本,可以產生預期的結果。
db.Notas.aggregate([{
$unwind: "$notas"
}, {
$group: {
_id: "resumo",
total_notas: { $sum: 1 },
soma_portal: { $sum: "$notas.valores.portal" },
soma_arquivo: { $sum: "$notas.valores.arquivo" },
abatimentos: { $push: "$notas.abatimentos" }
}
}, {
$unwind: "$abatimentos"
}, {
$unwind: "$abatimentos"
}, {
$group: {
_id: "$_id",
total_notas: { $first: "$total_notas" },
soma_portal: { $first: "$soma_portal" },
soma_arquivo: { $first: "$soma_arquivo" },
soma_abatimentos: { $sum: "$abatimentos.valor" }
}
}])
如果您能夠使用MongoDB> = 3.4,我建議使用另一種方法來減少文檔大小,並避免使用MongoDB 3.4中添加的$ reduce進行多個$ unwind操作
db.Notas.aggregate([{
$unwind: "$notas"
}, {
$project: {
_id: 0,
portal: "$notas.valores.portal",
arquivo: "$notas.valores.arquivo",
abatimentos: {
$reduce: {
input: "$notas.abatimentos",
initialValue: 0,
in: { $add: ["$$value", "$$this.valor"] }
}
}
}
}, {
$group: {
_id: "resumo",
total_notas: { $sum: 1 },
soma_portal: { $sum: "$portal" },
soma_arquivo: { $sum: "$arquivo" },
soma_abatimentos: { $sum: "$abatimentos" }
}
}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.