我的文档中有数组,我尝试接收该数组的最后一个元素。
我的代码是:
Post.find({_id:postId},{'comments':{'$slice':-1}});
这给了我所有的对象,但注释数组仅包含最后一个元素。
另一方面,
Post.find({_id:postId},{'comments':1});
只给我评论。
我不知道如何将这两个命令组合在一起。怎样才能做到呢?
{
"users":[],
"comments":["string1","string2","string3"],
"lastValue":"Wow"
"name":"jow"
"_id": {
"$oid": "5747d6bdecfae9d0560077cc"
},
}
Thanks
您可能想使用 mongodb(版本 3.2)聚合$slice https://docs.mongodb.com/manual/reference/operator/aggregation/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" }
}
}
]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)