在嵌套文档 MongoDB 中求和 [英] Sum in nested document MongoDB

查看:22
本文介绍了在嵌套文档 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆