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
Asked
Active
Viewed 187 times
3 Answers
0
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" } }
])
or
db.getCollection('notification').aggregate([
{
$project:
{
last: { statusList: [ "$slice", -1 ] }
}
}
])
and you can also take reference from: MongoDB - Query on the last element of an array?

Sandeep Kumar Nat
- 470
- 1
- 7
0
Try to use $last
aggregation operator.
db.getCollection('notification').aggregate([
{
$project:
{
_id: 0,
last: { $last:"$statusList"}
}
}
])

artiomi
- 383
- 2
- 7
-
whenever I use this I am getting this error, Error: Uncaught exception: Error: command failed: { "ok" : 0, "errmsg" : "Unrecognized expression '$last'", "code" : 168, "codeName" : "InvalidPipelineOperator" } : aggregate failed : – Akshay Kadu Oct 13 '22 at 14:45
0
Try with this, It gives the same output as $last:
db.getCollection('notification').aggregate([
{
$project:
{
last: { $arrayElemAt: [ "$project", -1 ] }
}
}
])

Sumit
- 407
- 1
- 8