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?

1
  • 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. As a workaround you will either have to implement the final sum in your application code or use Map/Reduce. Commented Dec 23, 2012 at 20:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.