Database
db={"Vote":[{postId:"1",comment:{text_sentiment:"positive",topic:"A"}},{postId:"2",comment:{text_sentiment:"negative",topic:"A"}},{postId:"3",comment:{text_sentiment:"positive",topic:"B"}},],"Post":[{_id:"1",tag:["a"]},{_id:"2",tag:["b"],}]}
Query
db.Vote.aggregate([{$match:{"comment":{$ne:null},"comment.topic":{$exists:1,$regex:".",$options:"i"}}},{$lookup:{from:"Post",let:{postId:"$postId"},pipeline:[{$match:{$expr:{$and:[{$eq:["$_id","$$postId"]},{$in:["a","$tag"]}]}}}],as:"tag"}},{$match:{$expr:{$gt:[{$size:"$tag"},0]}}},{$group:{_id:{topic:"$comment.topic",text_sentiment:"$comment.text_sentiment"},total:{$sum:1},postIds:{$push:"$postId"}}},{$group:{_id:"$_id.topic",total:{$sum:"$total"},text_sentiments:{$push:{k:"$_id.text_sentiment",v:"$total"}},postIds:{"$push":"$postIds"}}},{$project:{topic:"$_id",topicOccurance:"$total",sentiment:{"$arrayToObject":"$text_sentiments"},postIds:{$reduce:{input:"$postIds",initialValue:[],in:{$concatArrays:["$$value","$$this"]}}}}},{$sort:{"topicOccurance":-1}},{$addFields:{postIds:{"$setUnion":"$postIds"},tag:{"$setUnion":{$map:{input:"$tag",in:"$$this.tag"}}}}},])