按月分组MongoDB集合以及流失/收入图表的总收入

时间:2014-11-19 16:11:22

标签: mongodb business-intelligence

db.orders(仅限小摘录)

{ "_id" : "20101200221", "order_date" : ISODate("2010-12-12T13:11:15Z"), "net_revenue" : 19.36, "customer_id" : "aaa@gmx.net" }
{ "_id" : "20111003701", "order_date" : ISODate("2011-10-12T08:40:55Z"), "net_revenue" : 15.13, "customer_id" : "aaa@gmx.net" }
{ "_id" : "20111204977", "order_date" : ISODate("2011-12-07T09:13:47Z"), "net_revenue" : 15.13, "customer_id" : "aaa@gmx.net" }
{ "_id" : "20120206778", "order_date" : ISODate("2012-02-04T09:46:35Z"), "net_revenue" : 15.13, "customer_id" : "aaa@gmx.net" }
{ "_id" : "20120408856", "order_date" : ISODate("2012-04-15T10:37:55Z"), "net_revenue" : 12.65, "customer_id" : "aaa@gmx.net" }
{ "_id" : "20101200001", "order_date" : ISODate("2010-12-07T17:40:54Z"), "net_revenue" : 26.34, "customer_id" : "bbb@web.de" }
{ "_id" : "20100100473", "order_date" : ISODate("2011-01-31T06:38:03Z"), "net_revenue" : 34.34, "customer_id" : "bbb@web.de" }
{ "_id" : "20110601857", "order_date" : ISODate("2011-06-14T08:40:39Z"), "net_revenue" : 16.13, "customer_id" : "bbb@web.de" }
{ "_id" : "20111003719", "order_date" : ISODate("2011-10-13T06:43:50Z"), "net_revenue" : 60.75, "customer_id" : "bbb@web.de" }
{ "_id" : "20120912597", "order_date" : ISODate("2012-09-20T09:16:08Z"), "net_revenue" : 38.6, "customer_id" : "bbb@web.de" }
{ "_id" : "20130101745", "order_date" : ISODate("2013-01-28T11:40:17Z"), "net_revenue" : 20.14, "customer_id" : "bbb@web.de" }
{ "_id" : "20140615910", "order_date" : ISODate("2014-06-10T14:55:11Z"), "net_revenue" : 32.45, "customer_id" : "bbb@web.de" }`

创建流失/收入图表我需要按月对每个客户的初始/第一个订单进行分组。在摘录中你可以看到两个初始订单都在12/2010完成,所以以下所有订单都应归入此组,我们称之为1,第2组将是拥有初始订单01/2011等的所有人。 每个组都将是它自己的图形,并将像这样堆叠: enter image description here

组中的订单也必须再次分组为几个月,收入必须加总。 我希望我能说清楚我想要实现的目标!它整天都在试图找出如何为图表生成数据的方法。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望按客户和按月收入。

聚合查询中的$ group运算符正是您在这里寻找的。

db.orders.aggregate([
    { $group : { 
            _id: { 
                customer_id: "$customer_id",
                month: {$month: "$order_date"}
            },
            revenue: {$sum: "$net_revenue"} 
        }
    }], ... );

根据上述查询,如果客户在不同的月份订购,则会多次出现。我不明白这是不是你想要的。相反,如果您想要该客户的所有订单的总价值,但也按照他们订购的第一时间排序,请改为:

db.orders.aggregate([
    { $sort: { order_date : 1 } }, //order by date so that $first is correct
    { $group : { 
            _id: { 
                customer_id: "$customer_id",                
            },
            month: { $first: {$month: "$order_date"} }
            revenue: {$sum: "$net_revenue"} 
        }
    }], ... );