如何在mongodb聚合中对文档数组进行排序、获取其内容和长度?
假设我有一个如下所示的模式:如何在mongodb聚合中对文档数组进行排序、获取其内容和长度?,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,假设我有一个如下所示的模式: user = { id:'an id' username: 'some username' } post = { id:'an id' creater: 'some user id' postText: 'some text' } comment = { id:'an id' idOfPostThisCommentBelongsTo: 'some id' idOfCommenter: 'some id'
user = {
id:'an id'
username: 'some username'
}
post = {
id:'an id'
creater: 'some user id'
postText: 'some text'
}
comment = {
id:'an id'
idOfPostThisCommentBelongsTo: 'some id'
idOfCommenter: 'some id',
commentText: 'some text'
}
以下是我通过mongoose聚合函数创建的mongodb:
Post.aggregate([
{$match:{"_id" : 'idOfThePost'}},
{$lookup:{from:"users",localField:"creater",foreignField:"_id",as:"userWhoCreatedThisPost"}},
{$unwind:"$userWhoCreatedThisPost"},
{$lookup:{from:"comments",localField:"_id",foreignField:"idOfPostThisCommentBelongsTo",as:"comments"}},
// unwind, sort by date, grouping them back
{$unwind: {
"path": '$comments',
"preserveNullAndEmptyArrays": true
}},
{$sort: {'comments.createdAt': -1}},
{$group: {
_id: '$_id',
postText:{$first: '$postText'},
//how can I get the length of the comments' array????
'comments': {$push: '$comments'}
}},
// without the group pipeline this is how I can get the number of comments(see below)
// but when I try using the group pipeline(above) and project pipeline(below)
// and the aggregation doesn't work
{$project:{
numberOfComments:{$size:'comments'},
}}
我已经能够得到评论,甚至按日期排序。但我一直在努力
获取所有注释的长度
我知道我可以使用$first
获取上一个
文件。我试过注释:{$first:{$size:$comments}}
但它不起作用
如何获取评论数组的大小,同时仍然按日期对数组进行排序,同时仍然获取帖子和用户文档的值?
(例如,见下文)
基本上,每次他发现一条评论时,你都可以将你的组更改为总和1。大概是这样的:
$group: {
_id: '$_id',
'comments': {$sum: 1}
}
$group: {
_id: '$_id',
'comments': {$sum: 1}
}