$arrayElemAt new in MongoDB version 3.2.
db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
you can now use $arrayElemAt with ArrayOperators.ArrayElemAt class.
The above MongoDB projection would be traduced like the following for Spring Data Mongo:
project("name")
.and(ArrayOperators.ArrayElemAt.arrayOf("favorites").elementAt(0)).as("first")
.and(ArrayOperators.ArrayElemAt.arrayOf("favorites").elementAt(-1)).as("last")
DATAMONGO-1536 is about to add $arrayElemAt and other missing aggregation operators to Spring Data MongoDB for the Ingalls release. Meanwhile you can provide your own AggregationExpression to create whatever operation is needed.
For the above something like the following does the trick:
project("name") //
.and(context -> new BasicDBObject("$arrayElemAt", asList("$favorites", 0))).as("first")
.and(context -> new BasicDBObject("$arrayElemAt", asList("$favorites", -1))).as("last");