Tengo una colección llamada Vote que se parece a lo siguiente:
{ postId: "1", comment:{ text_sentiment: "positive", topic: "A" } }, // DOC-1 { postId: "2", comment:{ text_sentiment: "negative", topic: "A" } }, // DOC-2 { postId: "3", comment:{ text_sentiment: "positive", topic: "B" } },..//DOC-3 ..Quiero hacer una agregación en esta colección para que devuelva la siguiente estructura.
[ { _id: "hash", topic: "A", topicOccurance: 2, sentiment: { positive: 1, negative: 1, neutral: 0 }, postIds: [1,2] }, .. ]Creé la siguiente agregación:
db.Vote.aggregate([ { $match: { surveyId: "e6d38e1ecd", "comment.topic": { $exists: 1 }, } }, { $group: { _id: { topic: "$comment.topic", text_sentiment: "$comment.text_sentiment" }, total: { $sum: 1 }, } }, { $group: { _id: "$_id.topic", total: { $sum: "$total" }, text_sentiments: { $push: { k: "$_id.text_sentiment", v: "$total" } } } }, { $project: { topic: "$_id", topicOccurance: "$total", sentiment: { "$arrayToObject": "$text_sentiments" } } }, { $sort: { "topicOccurance": -1 } } ]) Esto funciona bien, pero no sé cómo puedo obtener también una matriz en la respuesta que contiene los postIds clave. Cada documento dentro del voto de la colección tiene postId de publicación y quiero agrupar las publicaciones que tienen el mismo tema y enviarlas a una matriz. ¿Cómo puedo hacer esto?
2da etapa ( $group ): agregue postId en la matriz postIds a través $push .
Tercera etapa ( $group ): agregue la matriz postIds a la matriz postIds a través $push . Esto hará que los postIds se conviertan en una matriz anidada.
[[1,2], ...] 4ta etapa ( $project ): para el campo postIds , use el operador $reduce para aplanar la matriz postIds por $concat . Actualización: con $setUnion a elementos distintos en la matriz.
db.collection.aggregate([ // match stage { $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: { $setUnion: [ { $reduce: { input: "$postIds", initialValue: [], in: { $concatArrays: [ "$$value", "$$this" ] } } } ] } } }, // sort stage ])