只获取数组 mongoose 的最后一个元素 [英] Get only the last element of array mongoose
本文介绍了只获取数组 mongoose 的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在文档中有数组,我尝试接收该数组的最后一个元素.
I have array in a document, and I try to receive the last element of this array.
我的代码是:
Post.find({_id:postId},{'comments':{'$slice':-1}});
这给了我所有的对象,但comments数组只包含最后一个元素.
this gives me all the object but the comments array contains only the last element.
另一方面,
Post.find({_id:postId},{'comments':1});
只给我评论.
我不知道如何将这两个命令组合在一起.怎么做?
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"
},
}
谢谢
推荐答案
您可能想要使用 mongodb(3.2 版)聚合 $slice 像这样:
You might want to use mongodb (version 3.2) aggregation $slice like that:
Post.aggregate([
{
$match: {
'_id.$oid': postId
}
},
{
$project: {
comments: {
$slice: [ "$comments", -1 ]
}
}
}
]);
在早期版本的 mongodb 中:
In earlier versions of mongodb:
Post.aggregate([
{
$match: {
'_id.$oid': postId
}
},
{
$unwind: "$comments"
},
{
$group : {
_id: "$_id.$oid",
comment: { $last: "$comments" }
}
}
]);
这篇关于只获取数组 mongoose 的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文