title: Node.js - how to calculate the aggregate(sum) of sub document in mongodb?
body: <p>My collection structure was, </p>
  
  <pre><code>[{
      "_id": "....",
      "name": "aaaa",
      "level_max_leaves": [{
          level: "ObjectIdString 1",
          max_leaves: 4,
      }]
  }, {
      "_id": "....",
      "name": "bbbb",
      "level_max_leaves": [{
          level: "ObjectIdString 1",
          max_leaves: 4,
      }]
  }, {
      "_id": "....",
      "name": "cccc",
      "level_max_leaves": [{
          level: "ObjectIdString 1",
          max_leaves: 7,
      }]
  }, {
      "_id": "....",
      "name": "dddd",
      "level_max_leaves": [{
          level: "ObjectIdString 2",
          max_leaves: 3,
      }]
  }]
  </code></pre>
  
  <p>Now I need to sum the field of <code>max_leaves</code> which has the <code>ObjectIdString 1</code>? </p>
  
  <p>And the result of <code>(4+4+7=15)</code>.</p>
  
  <p>so far I tried </p>
  
  <pre><code>var empLevelId = 1234... ;
  MyModel.aggregate(
      {$unwind: "$level_max_leaves.level"},
      {$match: {"$level_max_leaves.level": empLevelId } },
      {$group: { "_id": "$level_max_leaves.level", 
                 "total": { "$sum": "$level_max_leaves.max_leaves" }}},
      function (err, res) {
          console.log(res);
  });
  </code></pre>
  
  <p>How to achieve this?</p>