So I thought I should share them with the world! I said: "World - wouldn't you like to know how to do all kinds of cool stuff with MongoDB aggregation framework?" and world said ... well, pretty much nothing, so I took that as a "yes".
I'm not going to explain what MongoDB is or what Aggregation Framework is (since you're here, maybe you already know, if not just go and read the linked pages) and instead I'll dive right into some examples.
Imagine you have a lot of records like these:
{
"time" : ISODate("2013-03-08T22:25:24.973Z"),
"type": "annoying",
"PINGS" : 143
}
The basic aggregation query by type goes like this:
db.collection.aggregate({
"$group" : {
"_id" : "$type",
"count" : {
"$sum" : 1
},
"sum" : {
"$sum" : "$PINGS"
}
}
})
{"$project" : {
"type" : 1,
"PINGS" : 1,
"date" : "$time",
"_id" : 0,
"h" : {
"$hour" : "$time"
},
"m" : {
"$minute" : "$time"
},
"s" : {
"$second" : "$time"
},
"ml" : {
"$millisecond" : "$time"
}
}
}
{"$project" : {
"type" : 1,
"PINGS" : 1,
"date" : {
"$subtract" : [
"$date",
{
"$add" : [
"$ml",
{
"$multiply" : [
"$s",
1000
]
},
{
"$multiply" : [
"$m",
60,
1000
]
},
{
"$multiply" : [
"$h",
60,
60,
1000
]
}
]
}
]
}
}
}
{"$group" : {
"_id" : {
"type" : "$type",
"dt" : "$date"
},
"total" : {
"$sum" : "$PINGS"
},
"cnt" : {
"$sum" : 1
}
}
}
[
{
"_id" : {
"type" : "annoying",
"dt" : ISODate("2013-01-22T00:00:00Z")
},
"total":146,
"cnt" : 28
},
{
"_id" : {
"type" : "annoying",
"dt" : ISODate("2013-01-23T00:00:00Z")
},
"total" : 345,
"cnt" : 49
}, ...
Next time we'll talk about the tricky things we need to do to aggregate by days of the week. It's actually quite simple to extract day of the week from an ISODate - what's not so simple is to turn it into something human readable - like "Wednesday" instead of 4! I'll show you how I do it.