Home > Net >  how do i find last element of array list from MongoDB using aggregation function in spring?
how do i find last element of array list from MongoDB using aggregation function in spring?

Time:10-14

db.getCollection('notification').find({},{statusList:{$slice:-1}}) this query is getting expected outputs but from java, I could not find the solution for this. can anyone have a solution for this? I want to use only the aggregation function

CodePudding user response:

the aggregation operator $last can be used to access the last element of an array:

db.collection.aggregate([
  { $addFields: { last: { $last: "$yourArray" } } },
  { $match: { last: "C" } }
])

and you can also take reference from: MongoDB - Query on the last element of an array?

CodePudding user response:

Try to use $last aggregation operator.

 db.getCollection('notification').aggregate([
   {
     $project:
      {
         _id: 0,
         last: { $last:"$statusList"}
      }
   }
])

CodePudding user response:

Try with this, It gives the same output as $last:

 db.getCollection('notification').aggregate([
   {
     $project:
      {
         last: { $arrayElemAt: [ "$project", -1 ] }
      }
   }
])
  • Related