title: Getting single document position in MongoDB aggregate
body: <p>I am having troubles with what seems to be a simple problem in MongoDB but I haven't had much luck searching online.</p>
  <p>I have a collection that looks like this:</p>
  <pre><code>{ &quot;id&quot; : 'a18qv5k', &quot;name&quot; : &quot;Joe&quot;, &quot;myArray&quot; : ['foo']}
  { &quot;id&quot; : 'cbuesvhg', &quot;name&quot; : &quot;Adam&quot;, &quot;myArray&quot; : ['foo', 'bar', 'sample text']}
  { &quot;id&quot; : 'h106pw97', &quot;name&quot; : &quot;Bill&quot;, &quot;myArray&quot; : ['bar', 'lorem ipsum']}
  </code></pre>
  <p>I want to run an aggregation query to return the entire collection, sorted by the number of elements contained in myArray. I've already found a way to do that:</p>
  <pre><code>const aggregation = [{
      $project: {
          id: 0,
          name: 1,
          dim: {
              $size: '$myArray'
          }
      }
  }, {
      $sort: {
          dim: -1
      }
  }];
  </code></pre>
  <p>The next step (with which I am struggling) would be adding a <strong>position</strong> attribute to each projected document, showing its position in the returned collection. The result would look like:</p>
  <pre><code>{ &quot;name&quot; : &quot;Adam&quot;, dim : 3, position: 1}
  { &quot;name&quot; : &quot;Bill&quot;, dim: 2, position: 2}
  { &quot;name&quot; : &quot;Joe&quot;, dim: 1, position: 3}
  </code></pre>