Sample Mongo aggregation pipelines

How many Saga droids and Trilogy droids are there?

db.c.aggregate([
    {$match: {'race':'droid'}},
    {$group: {'_id':'$arc', 'num':{$sum:1}}}
])

What’s the max age for each race?

db.c.aggregate([
    {$match: {'race':{$exists:1}, 'age':{$exists:1}}},
    {$group: {'_id':'$race', 'maxage':{$max:'$age'}}},
    {$project: {'race':'$_id','maxage':1,'_id':0}}
])

What’s the average number of episodes for each race?

db.c.aggregate([
    {$match: {'race':{$exists:1}}},
    {$group: {'_id':'$race', 'avgeps':{$avg:{$size:'$episodes'}}}},
    {$sort:{'avgeps':-1}},
    {$project:{'species':'$_id', '_id':0, 'avgeps':1}},
    {$out:'race_episodes'}
])

How many characters in each episode?

db.c.aggregate([
    {$unwind: '$episodes'},
    {$group: {'_id': '$episodes', count: {'$sum':1}}},
    {$project: {'episode':'$_id', count:1, '_id':0 }},
    {$sort: {count: -1}}
])