twentysixmedias

Multi-Stage Aggregation SOlution

Sep 27th, 2018
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. db.getCollection('versus-challenges').aggregate([{
  2.     $match: {
  3.         type: {
  4.             $in: ['public','private']
  5.         }
  6.     }
  7. }, { // "uuids" is an array of uuids, so we split it
  8.     $unwind: '$uuids'
  9. }, { // Index by uuid+type, and add the challenges ID in an array
  10.     $group: {
  11.         _id: {
  12.             uuid: '$uuids',
  13.             type: '$type'
  14.         },
  15.         challenges: {
  16.             $addToSet: '$id'
  17.         }
  18.     }
  19. }, { // Split the array of challenge ID into multiple document to be able to $group again on them
  20.     $unwind: '$challenges'
  21. },{ // Group by uuid & type, count how many of each
  22.     $group: {
  23.         _id: {
  24.             uuid: '$_id.uuid',
  25.             type: '$_id.type'
  26.         },
  27.         challenges: {
  28.             $sum: 1
  29.         }
  30.     }
  31. },{ // Re-assemble into a single document per uuid
  32.     $group: {
  33.         _id: '$_id.uuid',
  34.         types_played: {
  35.             $sum: 1
  36.         },
  37.         played_total: {
  38.             $sum: '$challenges'
  39.         },
  40.         stats: {
  41.             $push: {
  42.                 type: '$_id.type',
  43.                 played: '$challenges'
  44.             }
  45.         }
  46.     }
  47. }, { // Sort to get the users who played the most on top
  48.     $sort: {
  49.         played_total: -1
  50.     }
  51. }])
Advertisement
Add Comment
Please, Sign In to add comment