0

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 }
  }
}])

Actual Result:

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

Expected Result:

[
  {
    "_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?

0

1 Answer 1

1

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

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.