tl;dr
What I have:
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"}
]
},
]
What I want to achieve:
{
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},
}
As you can see, here authorId and commentatorId fields contain an ObjectId key linking to another collection (lets say "users"). Any user can act as author or commentator. Even if user doesn't write any post, he still needs to be included in aggregation result. Number of comments needs to be counted in all posts, not only posts, which authorId equals to commentatorId.