Alon
Alon

Reputation: 2929

Get only the last element of array mongoose

I have array in a document, and I try to receive the last element of this array.

My code is:

Post.find({_id:postId},{'comments':{'$slice':-1}});

this gives me all the object but the comments array contains only the last element.

on the other hand,

Post.find({_id:postId},{'comments':1});

give me only the comments.

I dont find how to combine the two commands together. How it can be done?

{
 "users":[],
 "comments":["string1","string2","string3"],
 "lastValue":"Wow"
 "name":"jow"
 "_id": {
    "$oid": "5747d6bdecfae9d0560077cc"
   },
}

Thanks

Upvotes: 5

Views: 10827

Answers (4)

Sandesh
Sandesh

Reputation: 1044

I hope this helps.

db.Post.find(
  { _id: postId },
  { comments: { $slice: -1 }, _id: 0, users: 0, lastValue: 0, name: 0 },
);

Upvotes: 5

Muhammad Talha
Muhammad Talha

Reputation: 832

db.collection_name.find({'name':'how'},{'comments': {$slice: -1}})

Upvotes: 0

gprathour
gprathour

Reputation: 15333

In case of Mongoose, slice can work this way also,

model.find({ 
    // condition
})
.select('fields')
.slice('array', -1) // <------ Here
.then((data) => {
    // handle
})
.catch();

Just wrote pseudo code, as it might help someone.

Upvotes: 4

oleh.meleshko
oleh.meleshko

Reputation: 4795

You might want to use mongodb (version 3.2) aggregation $slice like that:

Post.aggregate([
  { 
    $match: { 
      '_id.$oid': postId 
    }
  },
  { 
    $project: {
      comments: {
        $slice: [ "$comments", -1 ] 
      }
    }
  }
]);

In earlier versions of mongodb:

Post.aggregate([
  { 
    $match: { 
      '_id.$oid': postId 
    }
  },
  { 
    $unwind: "$comments"
  },
  {
    $group : {
      _id: "$_id.$oid",
      comment: { $last: "$comments" }
    }
  }
]);

Upvotes: 6

Related Questions