Group by functions in Meteor for SUM and COUNT

670 views Asked by At

I'm building a simple app to track down all the purchase done by my business and I also want to track the total purchase done every month.

{
    "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
},

I need to display the sum of purchase made for each month

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

whenever a new item is added the total amount of each month should be updated real time

1

There are 1 answers

1
Harsh Patel On

If your data are in following Form :

/* 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")
}

You can use Following Aggregation Function :

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

Output :

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

Replace Month index with string later.