Home > Back-end >  mongodb: aggregate / group by array in array
mongodb: aggregate / group by array in array

Time:09-20

Assuming my cardgame matches collection has documents like these:

{
  match_id: 1,
  players: [
    {
      cards: [ "c03", "c15", "c22" ],
      result: 1
    },
    {
      cards: [ "c01", "c22", "c23" ],
      result: 0
    }
  ]
}

Now I want to determine which decks have been played and how often, meaning a list of all cards arrays, not a list of occurrences where two specific card arrays met.

I have tried this, which groups by match-ups:

db.collection.aggregate([{
  $group: {
    _id: "$players.cards",
    count: { $sum: 1 }
  }
}])

// result:
[
  {
    "_id": [
      [ "c03", "c15", "c22" ],
      [ "c01", "c22", "c23" ]
    ],
    "count": 3
  }, ...
]

// expected:
[
  {
    "_id": [ "c03", "c15", "c22" ],
    "count": 7
  },
  {
    "_id": [ "c01", "c22", "c23" ],
    "count": 5
  }, ...
]

How can I get an aggregation of distinct decks irrespective of specific matches?

CodePudding user response:

Your players field is an array, you need a $unwind stage to desconstruct the players array to multiple documents to avoid the result with _id (group) containing nested array.

db.collection.aggregate([
  {
    $unwind: "$players"
  },
  {
    $group: {
      _id: "$players.cards",
      count: {
        $sum: 1
      }
    }
  }
])

Demo @ Mongo Playground

  • Related