I mentioned a few days ago that sometimes we might want to aggregate data on day of the week. It's relatively simple to do that with MongoDB Aggregation Framework, but that does not mean that it's easy.
Imagine that you have this document:
Imagine that you have this document:
{
"time" : ISODate("2013-03-03T14:43:51.468Z"),
"quantity" : 5,
"totalPaid" : 5423
}
There may be other fields, but we mainly want to see how many items we sold by day of the week and for what average price. Imagine that totalPaid is expressed in cents (so the above document represents $54.23 paid for five items).
First we want to project to a document that has an additional field we need: day of the week.
First we want to project to a document that has an additional field we need: day of the week.
{
"$project" : {
"quantity" : 1,
"totalPaid" : 1,
"_id" : 0,
"dow" : {
"$dayOfWeek" : "$time"
}
}
}
This will turn our ISODate into an integer that represents day of the week - from 1 to 7. Next we want to do the aggregation grouping by this new field and computing the totals paid and total quantity.