0

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 3

0

Try to use $last aggregation operator.

 db.getCollection('notification').aggregate([
   {
     $project:
      {
         _id: 0,
         last: { $last:"$statusList"}
      }
   }
])
Sign up to request clarification or add additional context in comments.

1 Comment

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 :
0

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

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

Comments

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?

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.