Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use $arrayElemAt operator in Spring Data MongoDB

$arrayElemAt new in MongoDB version 3.2.

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

])

like image 416
Gaurav Krishna Avatar asked Sep 02 '25 03:09

Gaurav Krishna


1 Answers

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")
like image 129
charlycou Avatar answered Sep 05 '25 00:09

charlycou