title: Spring data MongoDb query based on last element of nested array field
body: <p>I have the following data (<strong>Cars</strong>):</p>
  
  <pre><code>[
      {
          "make" : “Ferrari”,
          "model" : “F40",
          "services" : [ 
              {
                  "type" : "FULL",
                  “date_time" : ISODate("2019-10-31T09:00:00.000Z"),
              }, 
              {
                  "type" : "FULL",
                  "scheduled_date_time" : ISODate("2019-11-04T09:00:00.000Z"),
              }
          ],
      },
      {
          "make" : "BMW",
          "model" : “M3",
          "services" : [ 
              {
                  "type" : "FULL",            
                  "scheduled_date_time" : ISODate("2019-10-31T09:00:00.000Z"),
              }, 
              {
                  "type" : "FULL",             
                  “scheduled_date_time" : ISODate("2019-11-04T09:00:00.000Z"),
              }
          ],
      }
  ]
  </code></pre>
  
  <p>Using Spring data MongoDb I would like a query to retrieve all the <strong>Cars</strong> where the <strong>scheduled_date_time</strong> of the <strong>last</strong> item in the <strong>services</strong> array is in-between a certain date range.</p>
  
  <p>A query which I used previously when using the first item in the services array is like:</p>
  
  <pre><code>mongoTemplate.find(Query.query(
          where("services.0.scheduled_date_time").gte(fromDate)
              .andOperator(
                  where("services.0.scheduled_date_time").lt(toDate))),
          Car.class);
  </code></pre>
  
  <p>Note the 0 index since it's first one as opposed to the last one (for my current requirement).</p>
  
  <p>I thought using an aggregate along with a projection and <code>.arrayElementAt(-1)</code> would do the trick but I haven't quite got it to work. My current effort is:</p>
  
  <pre><code>Aggregation agg = newAggregation(
          project().and("services").arrayElementAt(-1).as("currentService"),
          match(where("currentService.scheduled_date_time").gte(fromDate)
              .andOperator(where("currentService.scheduled_date_time").lt(toDate)))
      );
  
      AggregationResults&lt;Car&gt; results = mongoTemplate.aggregate(agg, Car.class, Car.class);
  
      return results.getMappedResults();
  </code></pre>
  
  <p>Any help suggestions appreciated.</p>
  
  <p>Thanks,</p>