I possess a variety of documents similar to the example displayed below as 3 distinct objects.
{
comment:{
text_sentiment: "positive",
topic: "A"
}
}, // DOC-1
{
comment:{
text_sentiment: "negative",
topic: "A"
}}, // DOC-2
{
comment:{
text_sentiment: "positive",
topic: "B"
}},..//DOC-3 ..
My goal is to construct an aggregation that produces outcomes in the format outlined below:
{
topic: "A",
topicOccurance: 2,
sentiment: {
positive: 3,
negative: 2,
neutral: 0
}
},...
I have devised an aggregation that successfully groups data by topic
and text_sentiment
, but I am uncertain about how to generate a structure resembling the one specified above. The aggregation I have created is presented below.
db.MyCollection.aggregate({
$match: {
_id: "xyz",
"comment.topic": {$exists: 1},
}
},{
$group: {
_id: {
topic: "$comment.topic",
text_sentiment: "$comment.text_sentiment"
},
total: {$sum: 1},
}
},{
$project: {
topic: {
name: "$_id.topic",
occurence: "$total"
},
sentiment: "$_id.text_sentiment"
}
},{
$sort: {"topic.occurence": -1}
})
Although it successfully divides data by topic
and sentiment
, the resulting structure does not match the desired format. How can I achieve a structure similar to the required one?