title: How to aggregate and sum deep nested arrays of same objects in MongoDB on a field
body: <p>I have a mongodb data as follows.</p>
  
  <pre><code>{
  "primaryCategory": "Orders",
  "sentiment": "POSITIVE",
  "date": ISODate("2017-01-12T09:00:00.000Z"),
  "commentDetails": [
      {
          "primaryCategory": "Products",
          "sentiment": "NEUTRAL",
          "date": ISODate("2017-01-12T09:00:00.000Z"),
          "commentDetails": [
              {
                  "primaryCategory": "Orders",
                  "sentiment": "NEGATIVE",
                  "date": ISODate("2017-01-12T09:00:00.000Z"),
                  "commentDetails": [
  
                  ]
              },
              {
                  "primaryCategory": "Responses",
                  "sentiment": "POSITIVE",
                  "date": ISODate("2017-01-12T09:00:00.000Z"),
                  "commentDetails": [
  
                  ]
              }
          ]
      },
      {
          "primaryCategory": "Orders",
          "sentiment": "NEUTRAL",
          "date": ISODate("2017-01-12T09:00:00.000Z"),
          "commentDetails": [
              {
                  "primaryCategory": "Products",
                  "sentiment": "NEGATIVE",
                  "date": ISODate("2017-01-12T09:00:00.000Z"),
                  "commentDetails": [
  
                  ]
              },
              {
                  "primaryCategory": "Orders",
                  "sentiment": "POSITIVE",
                  "date": ISODate("2017-01-12T09:00:00.000Z"),
                  "commentDetails": [
  
                  ]
              }
          ]
      }
  }
  </code></pre>
  
  <p>Here you can see that the below object is repeating as a nested array.</p>
  
  <pre><code>{
  "primaryCategory": "Orders",
  "sentiment": "POSITIVE",
  "date": ISODate("2017-01-12T09:00:00.000Z"),
  "commentDetails": []
  }
  </code></pre>
  
  <p>What I am looking for is, I have to aggregate and group this nested array of similar objects to produce result like below.</p>
  
  <pre><code>[
  {primaryCategory:"Orders",sentiment:[POSITIVE:3 /*Sum of all POSITIVE in Orders*/,NEGATIVE:5 /*Sum of all NEGATIVE in Orders*/,NEUTRAL:3 /*Sum of all NEUTRAL in Orders*/]},
  {primaryCategory:"Products",sentiment:[POSITIVE:3 /*Sum of all POSITIVE in Products*/,NEGATIVE:5 /*Sum of all NEGATIVE in Products*/,NEUTRAL:3 /*Sum of all NEUTRAL in Products*/]},
  {primaryCategory:"Responses",sentiment:[POSITIVE:3 /*Sum of all POSITIVE in Responses*/,NEGATIVE:5 /*Sum of all NEGATIVE in Responses*/,NEUTRAL:3 /*Sum of all NEUTRAL in Responses*/]}
  ]
  </code></pre>
  
  <p>So that the nested arrays are removed and the total count is taken by grouping the fields <strong>"primaryCategory"</strong> and <strong>"sentiment"</strong></p>
  
  <p>I have tried a number of times to get this working with no luck.
  I am a beginner in MongoDB and some one please help me achieve this.
  Thanks a lot.</p>