0

We have collection with documents like:

{ 
    "_id" : <ObjectId>, 
    "player" : <String>, 
    "params" : [
        ...,
        {
            "name" : "kills", 
            "value" : 10
        },
        {
            "name" : "deaths", 
            "value" : 10
        },
        {
            "name" : "assists", 
            "value" : 10
        },
        ...
    ]
}

Is there any way to get list of all players with calculated KDA? KDA=(kills+assists)/deaths

For example, like this:

[{
    "_id" : <ObjectId>,
    "player" : <String>,
    "kda" : 2.5
},
...
]

And how to execute queries on resulted collection? To find all players with KDA>10 etc. Thanks!

1
  • Would be much better if you had looked up this question, tried out something and share the code you have. Commented Jul 11, 2018 at 8:23

1 Answer 1

1

If the order in your params array is expected to be identical across all elements one way would be like this:

db.collection.aggregate({
    $addFields: {
        "kda": {
            $divide: [
                { $sum: [
                    { $arrayElemAt: [ "$params.value", 0 ] },
                    { $arrayElemAt: [ "$params.value", 2 ] }
                ]},
                { $arrayElemAt: [ "$params.value", 1 ] } ] 
        }
    }
})

If the order is not known or fixed you can do this:

db.collection.aggregate({
    $addFields: {
        "kda": {
            $divide: [
                { $sum: [
                    { $arrayElemAt: [ "$params.value", { $indexOfArray: [ "$params.name", "kills" ] } ] },
                    { $arrayElemAt: [ "$params.value", { $indexOfArray: [ "$params.name", "assists" ] } ] }
                ]},
                { $arrayElemAt: [ "$params.value", { $indexOfArray: [ "$params.name", "deaths" ] } ] } ] 
        }
    }

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

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.