4

$arrayElemAt new in MongoDB version 3.2.

db.users.aggregate([
{
 $project:
  {
     name: 1,
     first: { $arrayElemAt: [ "$favorites", 0 ] },
     last: { $arrayElemAt: [ "$favorites", -1 ] }
  }
}

])

3 Answers 3

9

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")
Sign up to request clarification or add additional context in comments.

Comments

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")

Comments

2

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.