Inspireret af dette eksempel på Mongos hjemmeside.
GENERER DUMMY DATA:
> db.stack.insert({a:1,b:1,c:1,active:1})
> db.stack.insert({a:1,b:1,c:2,active:0})
> db.stack.insert({a:1,b:2,c:3,active:1})
> db.stack.insert({a:1,b:2,c:2,active:0})
> db.stack.insert({a:2,b:1,c:3,active:1})
> db.stack.insert({a:2,b:1,c:10,active:1})
> db.stack.insert({a:2,b:2,c:10,active:0})
> db.stack.insert({a:2,b:2,c:5,active:1})
MONGO FORESPØRGSEL:
> db.stack.aggregate(
... {$match:{active:1}},
... {$group:{_id:{a:"$a", b:"$b"}, csum:{$sum:"$c"}}},
... {$sort:{"_id.a":1}})
RESULTAT:
{"result" : [
{"_id" : {"a" : 1,"b" : 2},"csum" : 3},
{"_id" : {"a" : 1,"b" : 1},"csum" : 1},
{"_id" : {"a" : 2,"b" : 2},"csum" : 5},
{"_id" : {"a" : 2,"b" : 1},"csum" : 13}
],"ok" : 1}
(BEMÆRK:Jeg omformaterede shell-resultatet lidt, så det er mere læsbart)