title: mongodb get document with max length of a specific array field nodejs
body: <p>This is type of document</p>
  <pre><code>{
    _id: string, 
    attributes: [{},{}],
    collection_name: string
  }
  </code></pre>
  <p>i want to get the id and attributes whose attributes length is maximum, so I am using this query</p>
  <pre><code>.aggregate([
              { $match: { collection_name: collection } },
              
              {
                $group: {
                  _id: null,
                  id: { &quot;$first&quot;: &quot;$_id&quot; },
                  attributes: { &quot;$first&quot;: &quot;$attributes&quot; },
                  maxLengthOfYArray: {
                    $max: {
                      $size: {
                        $ifNull: [&quot;$attributes&quot;, []]
                      }
                    }
                  }
                }
              }
            ]).toArray();
  </code></pre>
  <p>but this is returning correct max length but not the correct document, the document it returns has only 5 attributes</p>
  <p>what is the issue?</p>
  <p><strong>Update</strong></p>
  <p>documents</p>
  <pre><code>[
      {
          _id : &quot;1&quot;,
          attributes : [{a:1},{b:2}],
          collection_name : &quot;A&quot;
      },
      {
          _id : &quot;2&quot;,
          attributes : [{b:2}],
          collection_name : &quot;B&quot;
      }
  
  ]
  </code></pre>
  <p>and the result I am expecting</p>
  <pre><code>{
    _id: &quot;1&quot;,
    attributes : [{a:1},{b:2}],
    maxLengthOfArray : 2 
  }
  </code></pre>