Get out procentage out of mongodb aggreate

Viewed 23

I'm new to mongodb and I'm trying to get my mongodb aggreagt correct, but I'm missing something. I want this search to get procentage from specific playername.

I found this post and I have tried to replicate this but I don't have the same data.

Calculating percentage within a group in mongodb aggregate pipeline

This is a exemple of how my collection looks like:

{"_id":{"$oid":"630b25bc2256457d80760ec4"},"playersName":"yoyo","playersChoice":"Paper"}

{"_id":{"$oid":"630720244e62a26b17f38d03"},"playersChoice":"Scissor","playersName:":"nicklas"}

{"_id":{"$oid":"63071eca4e62a26b17f38d02"},"playersChoice":"Paper","playersName:":"nicklas"}

sampledata

Right now I get zero back

any advice?

1 Answers

Try this code where I am grouping by players name and counting the total for paper and scissor.

    db.collection.aggregate([
  {
    $group: {
      _id: {
        playersName: "$playersName"
      },
      playersChoice: {
        "$addToSet": "$playersChoice"
      },
      total: {
        $sum: 1
      }
    }
  },
  {
    $group: {
      _id: {
        playersChoice: "$playersChoice"
      },
      total: {
        $sum: "$total"
      }
    }
  }
])
Related