只获取数组mongoose的最后一个元素

我有一个文件中的数组,我试图接收这个数组的最后一个元素。

我的代码是:

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

这给了我所有的对象,但评论数组只包含最后一个元素。

另一方面,

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

只给我评论。

我没有find如何将两个命令结合在一起。 如何做到这一点?

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

谢谢

你可能想要像这样使用mongodb(版本3.2)聚合$ slice :

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

在早期版本的mongodb中:

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

我希望这有帮助。

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