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

时间:2016-05-27 05:23:39

标签: node.js mongodb mongoose

我在文档中有数组,我尝试接收该数组的最后一个元素。

我的代码是:

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

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

另一方面,

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

只给我评论。

我没有找到如何将两个命令组合在一起。怎么做?

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

由于

3 个答案:

答案 0 :(得分:2)

我希望这会有所帮助。

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

答案 1 :(得分:2)

您可能希望使用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" }
    }
  }
]);

答案 2 :(得分:1)

对于Mongooseslice也可以这样工作,

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

只需编写伪代码,因为它可能会对某人有所帮助。

相关问题