Operator $arrayElemAt in aggregation with Mongo < 3.2
<p>Using the <strong>aggregation</strong> framework in Mongo, </p>

<p>How can I achieve the same result in <strong>Mongo &lt; 3.2</strong>  as in <strong>Mongo 3.2</strong> with the operation <strong>$arrayElemAt</strong>?</p>

<p><strong>Example in Mongo 3.2</strong></p>

<p><em>Collection</em></p>

<pre><code>{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
</code></pre>

<p><em>Query</em></p>

<pre><code>db.users.aggregate([
   {
     $project:
      {
         name: 1,
         first: { $arrayElemAt: [ "$favorites", 0 ] },
         last: { $arrayElemAt: [ "$favorites", -1 ] }
      }
   }
])
</code></pre>

<p>It works fine</p>

<p>But, I have been forced to used Mongo 3.0 so I can't use this operator, which is ideal for what I want to do </p>

<p>Is there any way to accessing an element of an array by index with something like...</p>

<p><strong>Mongo 3.0</strong></p>

<p><em>Collection</em></p>

<pre><code>{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
</code></pre>

<p><em>Query</em></p>

<pre><code>db.users.aggregate([
   {
     $project:
      {
         name: 1,
         first: { "$favorites.0" },
         last:  { "$favorites.1" }
      }
   }
])
</code></pre>

<p>I tried and it doesn't work, it gives me an empty array.</p>

<p>However, when they are properties rather than indexes it is able to retrieve the values</p>

<p>Any help would be really appreciated.</p>

<p>Thanks</p>