title: MongoDB Max of Count
body: <p>Document structure:
  userId, name, product(Array)</p>
  
  <p>Requirement:
  Need to find a userId who has largest number of products.</p>
  
  <p>Tried to count the number product for userId using the below query 1, but not sure how to find the Max value out of it</p>
  
  <p>Query 1:</p>
  
  <pre><code>db.things.aggregate({$project:{id:"$userId",count:{$size:{"$ifNull":["$Product",[]]}}}})
  </code></pre>
  
  <p>Result:</p>
  
  <blockquote>
    <p>Id: 1    count:0</p>
    
    <p>Id: 2    count:7</p>
    
    <p>Id: 3    count:10</p>
  </blockquote>
  
  <p>End output should be like this:</p>
  
  <blockquote>
    <p>Id: 3    count:10</p>
  </blockquote>