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
3 Answers
Try to use $last aggregation operator.
db.getCollection('notification').aggregate([
{
$project:
{
_id: 0,
last: { $last:"$statusList"}
}
}
])
1 Comment
Akshay Kadu
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 :
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?