MongoDB深层嵌套聚合

时间:2018-06-07 15:03:53

标签: javascript mongodb mongoose aggregation-framework

TL;博士

我有什么:

  

db.posts.find()

[ 
  { authorId: 1, 
    text: "lorem",
    likes: 22 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 8, commentText: "trash"}
    ]
  }, 
  { authorId: 2, 
    text: "ipsum",
    likes: 33, 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 1, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
  { authorId: 3, 
    text: "ipsum",
    likes: 44, 
    comments: [
      { commentatorId: 2, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
  { authorId: 1, 
    text: "ipsum",
    likes: 55, 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
]

我想要实现的目标:

{ 
 1: {posts: 2, likes: 77, comments: 4}, 
 2: {posts: 1, likes: 33, comments: 4},
 3: {posts: 1, likes: 44, comments: 3},
 8: {posts: 0, likes: 0,  comments: 1},
}

如您所见,此处authorId和commentatorId字段包含链接到另一个集合的ObjectId键(假设"用户")。任何用户都可以充当作者或评论员。即使用户没有写任何帖子,他仍然需要包含在聚合结果中。需要在所有帖子中计算评论数量,而不仅仅是帖子,其中authorId等于commentatorId。

1 个答案:

答案 0 :(得分:0)

我认为这是你想要的东西

db.posts.aggregate([
{$unwind:"$comments"},
{$group:{_id:"$authorId", 
"likes":{$addToSet:"$likes"}, "comments":{$addToSet:"$comments"}}},
{$project:{"likes":{$sum:"$likes"}, "posts":{$size:"$likes"}, "comments":{$size:"$comments"}}}
])