0

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

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Bala S
  • 1
  • 2

1 Answers1

0

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.

Harsh Patel
  • 573
  • 6
  • 22
  • Aggregation requires more work on Meteor. See http://stackoverflow.com/questions/32473272/meteor-query-for-all-documents-with-unique-field – FullStack Sep 09 '15 at 08:38