Skip to content

Instantly share code, notes, and snippets.

@gentunian
Created August 7, 2015 15:35
Show Gist options
  • Save gentunian/cfb826d6ca49bd3d9e38 to your computer and use it in GitHub Desktop.
Save gentunian/cfb826d6ca49bd3d9e38 to your computer and use it in GitHub Desktop.
mongodb aggregation
{ "_id" : ObjectId("55c4cad542d5abb845ee68ab"), "date" : "1", "type" : "C" }
{ "_id" : ObjectId("55c4cad642d5abb845ee68ac"), "date" : "1", "type" : "C" }
{ "_id" : ObjectId("55c4cad842d5abb845ee68ad"), "date" : "1", "type" : "C" }
{ "_id" : ObjectId("55c4cadc42d5abb845ee68ae"), "date" : "1", "type" : "A" }
{ "_id" : ObjectId("55c4cadc42d5abb845ee68af"), "date" : "1", "type" : "A" }
{ "_id" : ObjectId("55c4cade42d5abb845ee68b0"), "date" : "1", "type" : "B" }
{ "_id" : ObjectId("55c4cae142d5abb845ee68b1"), "date" : "2", "type" : "B" }
{ "_id" : ObjectId("55c4cae242d5abb845ee68b2"), "date" : "2", "type" : "B" }
{ "_id" : ObjectId("55c4cae442d5abb845ee68b3"), "date" : "2", "type" : "A" }
{ "_id" : ObjectId("55c4cae542d5abb845ee68b4"), "date" : "2", "type" : "C" }
{ "_id" : ObjectId("55c4cae742d5abb845ee68b5"), "date" : "2", "type" : "C" }
{ "_id" : ObjectId("55c4caec42d5abb845ee68b6"), "date" : "3", "type" : "C" }
{ "_id" : ObjectId("55c4caed42d5abb845ee68b7"), "date" : "3", "type" : "C" }
{ "_id" : ObjectId("55c4caef42d5abb845ee68b8"), "date" : "3", "type" : "A" }
{ "_id" : ObjectId("55c4caef42d5abb845ee68b9"), "date" : "3", "type" : "A" }
{ "_id" : ObjectId("55c4caf042d5abb845ee68ba"), "date" : "3", "type" : "A" }
{ "_id" : ObjectId("55c4caf042d5abb845ee68bb"), "date" : "3", "type" : "A" }
{ "_id" : ObjectId("55c4caf142d5abb845ee68bc"), "date" : "3", "type" : "B" }
db.daily.aggregate([
{
$group: {
_id: { type:"$type", date: "$date" },
count: {$sum: 1}
}
}
])
Output:
{ "_id" : { "type" : "A", "date" : "3" }, "count" : 4 }
{ "_id" : { "type" : "B", "date" : "3" }, "count" : 1 }
{ "_id" : { "type" : "B", "date" : "2" }, "count" : 2 }
{ "_id" : { "type" : "C", "date" : "3" }, "count" : 2 }
{ "_id" : { "type" : "C", "date" : "2" }, "count" : 2 }
{ "_id" : { "type" : "B", "date" : "1" }, "count" : 1 }
{ "_id" : { "type" : "A", "date" : "1" }, "count" : 2 }
{ "_id" : { "type" : "A", "date" : "2" }, "count" : 1 }
{ "_id" : { "type" : "C", "date" : "1" }, "count" : 3 }
Desired output:
{"date" : "1", "A" : 2, "B" : 1, "C" : 3}
{"date" : "2", "A" : 1, "B" : 2, "C" : 2}
{"date" : "3", "A" : 4, "B" : 1, "C" : 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment