问题
$arrayElemAt new in MongoDB version 3.2.
db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
回答1:
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");
回答2:
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")
回答3:
Even more concise, you can even use $arrayElementAt as follows:
project("name")
.and("favorites").arrayElementAt(0).as("first")
.and("favorites").arrayElementAt(-1).as("last")
来源:https://stackoverflow.com/questions/40909320/how-to-use-arrayelemat-operator-in-spring-data-mongodb