title: MongoDB: Aggregation Group operation over a dynamic key-value pair
body: <p>I have a simple document with one field as a key-value pair. I want to just perform a group operation in Aggregation over those keys and add their values. But the keys in the pair are not fixed and can be anything.</p>
  
  <p>Here is a sample document.</p>
  
  <pre><code>{
      _id: 349587843,
      matchPair: {
          3 : 21,
          9 : 4,
          7 : 32
      }
  },
  {
      _id: 349587478,
      matchPair: {
          7 : 11,
          54 : 32,
          9 : 7,
          2 : 19
      }
  }
  </code></pre>
  
  <p>And I want a result something like the following.</p>
  
  <pre><code>{
      _id : 3,
      count : 21
  },
  {
      _id : 9,
      count : 11
  },
  {
      _id : 7,
      count : 43
  },
  {
      _id : 54,
      count : 32
  },
  {
      _id : 2,
      count : 19
  }
  </code></pre>
  
  <p>I have the following query in mind and tried using <code>$unwind</code>operation but it doesn't work probably because "matchPair" isn't an array and I don't know what to specify for the <code>$sum</code>operation.</p>
  
  <pre><code>db.MatchPairs.aggregate([
     { "$unwind" : "$matchPair" },
     { "$group" : {
         _id: "$matchPair",
         count : { $sum : $matchPair }
     } }
  ]);
  </code></pre>
  
  <p>I could also try Map-Reduce but for that too I need to <code>emit()</code> keys and values by name.</p>
  
  <p>I'm sure there's a simple solution to this but I can't figure it out.</p>