title: How to get the recent values of grouped result?
body: <p>Below is the document which has an array name datum and I want to filter the records based on StatusCode, group by Year and sum the amount value from the recent record of distinct Types.</p>
  <pre><code>    {
      &quot;_id&quot; : ObjectId(&quot;5fce46ca6ac9808276dfeb8c&quot;),
      &quot;year&quot; : 2018,
      &quot;datum&quot; : [ 
          {
              &quot;StatusCode&quot; : &quot;A&quot;,
              &quot;Type&quot; : &quot;1&quot;,
              &quot;Amount&quot; : NumberDecimal(&quot;100&quot;),
              &quot;Date&quot; : ISODate(&quot;2018-05-30T00:46:12.784Z&quot;)
          }, 
          {
              &quot;StatusCode&quot; : &quot;A&quot;,
              &quot;Type&quot; : &quot;1&quot;,
              &quot;Amount&quot; : NumberDecimal(&quot;300&quot;),
              &quot;Date&quot; : ISODate(&quot;2023-05-30T00:46:12.784Z&quot;)
          }, 
          {
              &quot;StatusCode&quot; : &quot;A&quot;,
              &quot;Type&quot; : &quot;2&quot;,
              &quot;Amount&quot; : NumberDecimal(&quot;420&quot;),
              &quot;Date&quot; : ISODate(&quot;2032-05-30T00:46:12.784Z&quot;)
          },
          
          {
              &quot;StatusCode&quot; : &quot;B&quot;,
              &quot;Type&quot; : &quot;2&quot;,
              &quot;Amount&quot; : NumberDecimal(&quot;420&quot;),
              &quot;Date&quot; : ISODate(&quot;2032-05-30T00:46:12.784Z&quot;)
          }
      ]
  }
  </code></pre>
  <p>In my case following is the expected result :</p>
  <pre><code>{
    Total : 720
  }
  </code></pre>
  <p>I want to achieve the result in the following aggregate Query pattern</p>
  <pre><code> db.collection.aggregate([
        {
          $addFields: {
            datum: {
              $reduce: {
                input: &quot;$datum&quot;,
                initialValue: {},
                &quot;in&quot;: {
                  $cond: [
                    {
                      $and: [
                        { $in: [&quot;$$this.StatusCode&quot;, [&quot;A&quot;]] }                     
                      ]
                    },
                    &quot;$$this&quot;,
                    &quot;$$value&quot;
                  ]
                }
              }
            }
          }
        },
        {
          $group: {
            _id: &quot;$year&quot;,
            RecentValue: { $sum: &quot;$datum.Amount&quot; }
          }
        }
      ])
  </code></pre>