title: Mongodb group by and sum and get media with Map
body: <p>I have these collections in my database:</p>
  
  <p><strong>Items:</strong></p>
  
  <pre><code>{ "IdUser" : "1", "IdItem" : "1" },
  { "IdUser" : "1", "IdItem" : "2" },
  { "IdUser" : "1", "IdItem" : "3" },
  { "IdUser" : "2", "IdItem" : "4" },
  { "IdUser" : "2", "IdItem" : "5" },
  { "IdUser" : "4", "IdItem" : "6" },
  { "IdUser" : "5", "IdItem" : "7" }
  </code></pre>
  
  <p><strong>Users</strong></p>
  
  <pre><code>{ "_id" : "1", "DateRegister" : ISODate("2016-03-29T22:00:38.764+0000") },
  { "_id" : "2", "DateRegister" : ISODate("2014-03-29T22:00:38.764+0000") },
  { "_id" : "2", "DateRegister" : ISODate("2015-02-29T22:00:38.764+0000") },
  { "_id" : "4", "DateRegister" : ISODate("2013-01-29T22:00:38.764+0000") },
  { "_id" : "5", "DateRegister" : ISODate("2016-04-29T22:00:38.764+0000") }
  </code></pre>
  
  <p>How can I obtain this result but FILTERED with users registered after <strong>2015</strong>:</p>
  
  <blockquote>
    <p>Users with one item: 2</p>
    
    <p>Users with two items: 1</p>
    
    <p>Users with three items: 1</p>
  </blockquote>
  
  <p>I have tried with that, but I don't know how to filter... Thanks!</p>
  
  <pre><code>db.collection.aggregate([
      {
          "$group": {
              "_id": "$IdUser",
              "count": { 
                  "$sum": { "$cond": [{ "$gt": [ "$IdItem", null ] }, 1, 0 ] } 
              }            
          }
      },
      {
          "$group": {
              "_id": "$count",
              "users": { "$push": "$_id" }            
          }
      },
      {
          "$project": {
              "_id": 0, 
              "number_of_items": "$_id", 
              "number_of_users": { "$size": "$users" } 
          }
      }
  ])
  </code></pre>