[英]Get only the last element of array mongoose
我在文档中有数组,我尝试接收该数组的最后一个元素。
我的代码是:
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"
},
}
谢谢
我希望这会有所帮助。
db.Post.find({_id:postId},{'comments':{'$slice':-1},_id:0,users:0,lastValue:0,name:0});
您可能想像这样使用 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" }
}
}
]);
在Mongoose
情况下, slice
也可以这样工作,
model.find({
// condition
})
.select('fields')
.slice('array', -1) // <------ Here
.then((data) => {
// handle
})
.catch();
刚刚写了伪代码,因为它可能对某人有所帮助。
db.collection_name.find({'name':'how'},{'comments': {$slice: -1}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.