Skip to content

Instantly share code, notes, and snippets.

@jamesoff
Created November 27, 2013 19:49
Show Gist options
  • Save jamesoff/7682082 to your computer and use it in GitHub Desktop.
Save jamesoff/7682082 to your computer and use it in GitHub Desktop.
MongoDB training aggregation exercises
db.twitter.aggregate(
{ $group : {
"_id" : "$user.screen_name",
"tweets" : { $sum : 1 }
}
},
{ $sort : { "tweets" : -1 } },
{ $limit : 5 }
)
db.twitter.aggregate(
{ $unwind : "$entities.user_mentions" },
{ $group : { "_id" : "$user.screen_name",
"does_mention" : { $sum : 1 } }
},
{ $sort : { "does_mention" : -1 } },
{ $limit : 5 }
)
db.twitter.aggregate(
{ $unwind : "$entities.user_mentions" },
{ $group : {
"_id" : "$user.screen_name",
"mentioned" : { $addToSet : "$entities.user_mentions.screen_name" }
}
},
{ $unwind : "$mentioned" },
{ $group : {
"_id" : "$_id",
"mention_count" : { $sum : 1 }
}
},
{ $sort : { "mention_count" : -1 } },
{ $limit : 5 }
)
// Highest ratio
db.twitter.aggregate(
{ $match : {
"user.friends_count" : { $gt : 0 } ,
"user.followers_count" : { $gt : 0 }
}
},
{ $project : {
"user.screen_name" : 1,
"ratio" : { $divide : [ "$user.followers_count", "$user.friends_count" ] },
"user.friends_count" : 1,
"user.followers_count" : 1
}
},
{ $sort : { "ratio" : -1 } },
{ $limit : 1 }
)
// Lowest ratio
db.twitter.aggregate(
{ $match : {
"user.friends_count" : { $gt : 0 } ,
"user.followers_count" : { $gt : 0 }
}
},
{ $project : {
"user.screen_name" : 1,
"ratio" : { $divide : [ "$user.followers_count", "$user.friends_count" ] },
"user.friends_count" : 1,
"user.followers_count" : 1
}
},
{ $sort : { "ratio" : 1 } },
{ $limit : 1 }
)
// Average ratio
db.twitter.aggregate(
{ $match : {
"user.friends_count" : { $gt : 0 } ,
"user.followers_count" : { $gt : 0 }
}
},
{ $project : {
"user.screen_name" : 1,
"ratio" : { $divide : [ "$user.followers_count", "$user.friends_count" ] },
"user.friends_count" : 1,
"user.followers_count" : 1
}
},
{ $group : {
_id : "whatever",
"sum" : { $sum : "$ratio" },
"count" : { $sum : 1 },
}
},
{ $project : {
_id : 1,
avg : { $divide : [ "$sum", "$count" ] }
}
}
)
// Closest to average
db.twitter.aggregate(
{ $match : {
"user.friends_count" : { $gt : 0 } ,
"user.followers_count" : { $gt : 0 }
}
},
{ $project : {
"user.screen_name" : 1,
"ratio" : { $divide : [ "$user.followers_count", "$user.friends_count" ] },
"user.friends_count" : 1,
"user.followers_count" : 1
}
},
{ $project : {
"user.screen_name" : 1,
"difference" : { $subtract : [ "$ratio", 8.044204413696734 ] }
}
},
{ $project : {
"user.screen_name" : 1,
"abs_difference" : {
$cond : [
{ $lt : [ "$difference", 0 ] },
{ $multiply : [ "$difference", -1 ] },
"$difference"
]
}
}
},
{ $sort : { "abs_difference" : 1 } },
{ $limit : 1 }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment