Reputation: 3797
I want to have a graph that show how many purchases was made on each day. The user should then be able to switch between showing purchases made today, last 7 days and last 30 days
Say I have a lot of these (simplfied) documents
purchase: {
itemId: 'some id'
createdAt: 'some date..'
}
I want to get an array of elements, each corresponding to the number of times a 'purchase' documents created on that day occurs.
I have tried fiddling around with the mongo aggregation framework, but hasnt been able to create a query that manages this.
Upvotes: 0
Views: 48
Reputation: 1786
This query will group purchases by the day
db.purchases.aggregate([
{$match: {createdAt: {$gte: new Date(2014, 0, 1)}}},
{$group: {_id: {year : {$year :'$createdAt'},
month: {$month :'$createdAt'}
day: {$dayOfMonth: '$createdAt'}
},
count: {$sum: 1}
}
])
You can try to limit the documents by adjusting the $match so it returns you purchases only from last 30 days.
If you would like to group the results by month, remove the "day" from the id.
Upvotes: 2