嵌套文档MongoDB中的总和 [英] Sum in nested document MongoDB
本文介绍了嵌套文档MongoDB中的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对文档数组中的一些值求和,但是没有运气.
I'm trying to sum some values in an array of documents, with no luck.
这是文档
db.Cuentas.find().pretty()
db.Cuentas.find().pretty()
{
"Agno": "2013",
"Egresos": [
{
"Fecha": "28-01-2013",
"Monto": 150000,
"Detalle": "Pago Nokia Lumia a @josellop"
},
{
"Fecha": "29-01-2013",
"Monto": 4000,
"Detalle": "Cine, Pelicula fome"
}
],
"Ingresos": [],
"Mes": "Enero",
"Monto": 450000,
"Usuario": "MarioCares"
"_id": ObjectId(....)
}
因此,我需要"Usuario":"MarioCares" 中"Egresos"中所有"Monto"的总和.在此示例中, 154000
So, i need the sum of all the "Monto" in "Egresos" for the "Usuario": "MarioCares". In this example 154000
我使用聚合:
db.Cuentas.aggregate(
[
{ $match: {"Usuario": "MarioCares"} },
{ $group:
{
_id: null,
"suma": { $sum: "$Egresos.Monto" }
}
}
]
)
但是我总是得到
{ "result" : [{ "_id" : null, "suma" : 0 }], "ok" : 1 }
我在做什么错了?
PD 已经看到此
推荐答案
如Sammaye所述,您需要 $unwind
Egresos
数组可为每个数组元素复制匹配的文档,因此您可以在每个元素上$sum
:
As Sammaye indicated, you need to $unwind
the Egresos
array to duplicate the matched doc per array element so you can $sum
over each element:
db.Cuentas.aggregate([
{$match: {"Usuario": "MarioCares"} },
{$unwind: '$Egresos'},
{$group: {
_id: null,
"suma": {$sum: "$Egresos.Monto" }
}}
])
这篇关于嵌套文档MongoDB中的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文