MongoDB按日期和名称分组,并加上金额

时间:2018-12-01 08:43:29

标签: mongodb

我的文档结构示例:

    {
    name: 'John',
    amount: '450.00'
    created_date: '1542283200000'
    },
    {
    name: 'Mark',
    amount: '890.00'
    created_date: '1542851379000'
    },
    {
    name: 'Chris',
    amount: '450.00'
    created_date: '1542851379000'
    },
    {
    name: 'Jack',
    amount: '230.00'
    created_date: '1542851379000'
    }...

我想要金额的总和,按日期和名称分组。假设我通过了from_date和to_date(间隔3天)的过滤器,我应该得到:

    {
    name: 'John', amount: '990', date: '20/11'
    },
    {
    name: 'John', amount: '200', date: '21/11'
    },
    {
    name: 'John', amount: '120', date: '22/11'
    },
    {
    name: 'Mark', amount: '323', date: '20/11'
    },
    {
    name: 'Mark', amount: '523', date: '21/11'
    },
    {
    name: 'Mark', amount: '734', date: '22/11'
    },
    {
    name: 'Chris', amount: '353', date: '20/11'
    },
    {
    name: 'Chris', amount: '744', date: '21/11'
    },
    {
    name: 'Chris', amount: '894', date: '22/11'
    },
    {
    name: 'Jack', amount: '534', date: '20/11'
    },
    {
    name: 'Jack', amount: '663', date: '21/11'
    },
    {
    name: 'Jack', amount: '235', date: '22/11'
    }

我了解MongoDb的基础知识,并且能够按名称提取按组汇总的记录。我也经历了这个link,但是我无法使用它,因为在这里他们正在使用ISO时间(我有时间戳)并且仅按一个属性分组。

1 个答案:

答案 0 :(得分:1)

这里的主要困难是将日期(时间戳)和金额都存储为字符串。因此,由于存在$toLong$toDate$toDouble运算符,因此在MongoDB 4.0或更高版本中可能很容易解决。因此,将时间戳记设为ISODate时,您可以使用$dateToParts,这将为您提供日期,月份等单独的字段。然后您可以按(day, month, name)分组并使用$sum来计算总金额。试试:

db.col.aggregate([
    {
        $addFields: {
            created_date: { $dateToParts: { date: { $toDate: { $toLong: "$created_date" } } } }
        }
    },
    {
        $group: {
            _id: { 
                name: "$name",
                day: "$created_date.day",
                month: "$created_date.month"
            },
            amount: { $sum: { $toDouble: "$amount" } }
        }
    },
    {
        $project: {
            _id: 0,
            name: "$_id.name",
            amount: 1,
            date: { $concat: [ { $toString: "$_id.day" }, "/", { $toString: "$_id.month" } ] }
        }
    }
])

输出:

{ "amount" : 230, "name" : "Jack", "date" : "22/11" }
{ "amount" : 450, "name" : "Chris", "date" : "22/11" }
{ "amount" : 890, "name" : "Mark", "date" : "22/11" }
{ "amount" : 450, "name" : "John", "date" : "15/11" }