skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. Try to use $last aggregation operator.

     db.getCollection('notification').aggregate([
       {
         $project:
          {
             _id: 0,
             last: { $last:"$statusList"}
          }
       }
    ])
    
    Login or Signup to reply.
  3. Try with this, It gives the same output as $last:

     db.getCollection('notification').aggregate([
       {
         $project:
          {
             last: { $arrayElemAt: [ "$project", -1 ] }
          }
       }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search