Cut array in MongoDB aggregation structure

I save the results of the game in MongoDB and want to calculate the sum of the three best results for each player.

Using the aggregation structure, I can build the following intermediate result of the pipeline from my database of ready-made games (each player below completed 5 games with a rating):

{ "_id" : "Player1", "points" : [ 324, 300, 287, 287, 227] }, { "_id" : "Player2", "points" : [ 324, 324, 300, 287, 123] } 

Now I need to summarize the three best values ​​for each player. I managed to sort the array, so it would be nice to get only the first 3 elements of each array in order to build the sum of the array in the next step of the transition.

$ limit will work fine if I only need a single player result. I also tried using $ slice, but this does not seem to work in the aggregation structure.

So, how do I get the sum of the top three results for each player?

+4
source share
2 answers

You mentioned that it would also be ok here to get only the first 3 elements of each array to build the sum of the array in the next pipeline step. do it first and then use:

 db.test.aggregate({'$unwind':'$points'},{'$group':{'_id':'$_id','result':{'$sum':'$points'}}} 

to get the result.

0
source

The $ slice method for the aggregation structure was added in version 3.2 of mongo. For a more detailed answer, see here .

And a few examples from the Mongo page:

 { $slice: [ [ 1, 2, 3 ], 1, 1 ] } // [ 2 ] { $slice: [ [ 1, 2, 3 ], -2 ] } // [ 2, 3 ] { $slice: [ [ 1, 2, 3 ], 15, 2 ] } // [ ] { $slice: [ [ 1, 2, 3 ], -15, 2 ] } // [ 1, 2 ] 
0
source

All Articles