title: Mongo Aggregate: Sum Count Field of Duplicate Array Value Field
body: <p>I have a huge bunch of documents as such:</p>
  
  <pre><code>{
    _id: '1',
    colors: [
      { value: 'red', count: 2 },
      { value: 'blue', count: 3}
    ]
    shapes: [
      { value: 'cube', type: '3d' },
      { value: 'square', type: '2d'}
    ]
  },    
  {
    _id: '2',
    colors: [
      { value: 'red', count: 7 },
      { value: 'blue', count: 34},
      { value: 'yellow', count: 12}
    ]
    shapes: [
      { value: 'prism', type: '3d' },
      { value: 'triangle', type: '2d'}
    ]
  }
  </code></pre>
  
  <p>By using <code>$unwind</code> and <code>$addToSet</code>, as such:</p>
  
  <pre><code>db.getCollection('coll').aggregate([{$unwind:"$colors"},{$unwind:"$shapes"},{$group:{_id:null,colors:{$addToSet:"$colors"},shapes:{$addToSet:"$shapes"}])
  </code></pre>
  
  <p>I can get the following:</p>
  
  <pre><code>{
      "_id" : null,
      "colors" : [ 
          { "value" : "red", "count" : 2 }, 
          { "value" : "blue", "count" : 3 }, 
          { "value" : "red", "count" : 7 }, 
          { "value" : "blue", "count" : 34 }, 
          { "value" : "yellow", "count" : 12 }
      ]
      "shapes" : [
          { value: 'cube', type: '3d' },
          { value: 'square', type: '2d'}
          { value: 'prism', type: '3d' },
          { value: 'triangle', type: '2d'}
      ]
  }
  </code></pre>
  
  <p>What I want however is to judge duplicates sole by the field "value" and sum up the "count" field for duplicates, i.e.</p>
  
  <pre><code>{
      "_id" : null,
      "colors" : [ 
          { "value" : "red", "count" : 9 }, 
          { "value" : "blue", "count" : 37 },  
          { "value" : "yellow", "count" : 12 }
      ]
      "shapes" : [
          { value: 'cube', type: '3d' },
          { value: 'square', type: '2d'}
          { value: 'prism', type: '3d' },
          { value: 'triangle', type: '2d'}
      ]
  }
  </code></pre>
  
  <p>This <a href="https://stackoverflow.com/questions/11189243/unwind-an-object-in-aggregation-framework">question</a> suggests that I could use <code>$colors.value</code> as an <code>_id</code> field and <code>$sum</code> to total the <code>count</code>. However, as I have a second array to <code>$unwind</code> and aggregate/<code>$group</code>, I am unsure of the best way to go about doing this.</p>