5

I am saving game results in MongoDB and would like to calculate the sum of the 3 best results for every player.

With the aggregation framework I am able to built the following intermediate pipeline result from my database of finished games (each player below has finished 5 games with the gives score):

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

Now I need to sum up the three best values for each player. I was able to sort the array so 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.

$limit would work fine if I only need the result for one player. I also tried using $slice but that doesn't seem to work in the aggregation framework.

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

StefanMK
  • 1,313
  • 1
  • 12
  • 22
  • 2
    Unfortunately there is no array indexing or `$slice` operator in the aggregation framework (as at MongoDB 2.2.2). There is an existing feature request you can vote on and watch: [SERVER-4589](https://jira.mongodb.org/browse/SERVER-4589). As a workaround you will either have to implement the final sum in your application code or use Map/Reduce. – Stennie Dec 23 '12 at 20:47

2 Answers2

0

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., so do it first, then use:

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

to get the result.

coderLMN
  • 3,076
  • 1
  • 21
  • 26
  • I think that you have misunderstood me. It would be ok to get the first three elements here (the first 3 out of 5), then I could sum up the whole array (with the 3 elements), similiar to what you did. However I do not know how to get the 3 best values before, I am only able to grab the whole array. – StefanMK Dec 23 '12 at 19:56
0

$slice method for aggregation framework was added in 3.2 version of mongo. For a more detailed answer, take a look here.

And a couple of 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 ]
Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753