按照Meteor中的函数分组和COUNT

时间:2015-06-08 06:41:43

标签: mongodb meteor aggregation-framework

我正在建立一个简单的应用程序,以追踪我的业务所做的所有购买,而且我还想跟踪每月完成的总购买量。

{
    "id": 264,
    "Name": "Item 1",
    "Price": US$ 15,
    "Date": 12 May 2015
}, {
    "id": 63,
    "Name": "Item 3",
    "Price": US$ 12,
    "Date": 19 May 2015
}, {
    "id": 16,
    "Name": "Item 1",
    "Price": US$ 22.5,
    "Date": 21 May 2015
}, {
    "id": 4,
    "Name": "Item 2",
    "Price": US$ 27.75,
    "Date": 21 May 2015
}, {
    "id": 4,
    "Name": "Item 2",
    "Price": US$ 27.75,
    "Date": 6 June 2015
},

我需要显示购买的总和     每个月

{
    "Month": "May",
    "Total": 77.25
}, {
    "Month": "June",
    "Total": 27.75
}

每当添加新项目时,每个月的总金额应实时更新

1 个答案:

答案 0 :(得分:0)

如果您的数据采用以下格式:

/* 0 */
{
    "_id" : 264,
    "Name" : "Item 1",
    "Price" : 15,
    "Date" : ISODate("2015-05-12T13:45:39.736+05:30")
}

/* 1 */
{
    "_id" : 63,
    "Name" : "Item 3",
    "Price" : 12,
    "Date" : ISODate("2015-05-19T13:45:39.736+05:30")
}

/* 2 */
{
    "_id" : 16,
    "Name" : "Item 1",
    "Price" : 22.5,
    "Date" : ISODate("2015-05-21T13:45:39.736+05:30")
}

/* 3 */
{
    "_id" : 4,
    "Name" : "Item 2",
    "Price" : 27.75,
    "Date" : ISODate("2015-05-21T13:45:39.736+05:30")
}

/* 4 */
{
    "_id" : 5,
    "Name" : "Item 2",
    "Price" : 27.75,
    "Date" : ISODate("2015-06-06T13:45:39.736+05:30")
}

您可以使用以下聚合功能:

db.collectionName.aggregate(
    { $project : { month : { $month : "$Date" }, price : "$Price"} },
    { $group : { _id : "$month" , "Total" : { $sum : "$price"}}},
    { $project : { Month : "$_id", "Total" : "$Total", "_id" : 0} }
)

输出:

/* 0 */
{
    "result" : [ 
        {
            "Total" : 27.75,
            "Month" : 6
        }, 
        {
            "Total" : 77.25,
            "Month" : 5
        }
    ],
    "ok" : 1
}

稍后用字符串替换月份索引。