MongoDB nested group?

I am trying to implement a nested group request in mongodb and I am getting stuck trying to add an external group. Given the following (simplified) data document:

{ "timestamp" : ISODate(), "category" : "movies", "term" : "my movie" } 

I am trying to get a list of all categories, and within the categories should be the maximum number of terms. I would like my output to be something like this:

 [ { category: "movies", terms: [ { term: "movie 1", total: 5000 }, { term: "movie 2", total: 200 } ... ] }, { category: "sports", terms: [ { term: "football 1", total: 4000 }, { term: "tennis 2", total: 250 } ... ] }, ] 

My “inner group” is shown below and will get the top 5 for all categories:

 db.collection.aggregate([ { $match : { "timestamp": { $gt: ISODate("2014-08-27") } } }, { $group : { _id : "$term", total : { $sum : 1 } } }, { $sort : { total : -1 } }, { $limit: 5 } ]); // Outputs: { "_id" : "movie 1", "total" : 943 } { "_id" : "movie 2", "total" : 752 } 

How can I implement an “external group”?

In addition, the above total ion returns a null value (not all documents have the meaning of a term). How can I ignore null values?

early

+13
mongodb mongodb-query
source share
2 answers

In this case, you will need two groups. The first group generates a document flow with one document for the period and category:

  { $group : { _id : { category: "$category", term: "$term", }, total: { $sum : 1 } } } 

The second group combines all documents with the same term into one, using the $ push operator to combine categories into an array:

  { $group : { _id : "$_id.category", terms: { $push: { term:"$_id.term", total:"$total" } } } } 
+19
source share

Request:

  db.getCollection('organica_sidu').aggregate([ {$match:{ tipo: {$regex:"[AZ]+"} } }, {$group: { _id:{ codigo:"1", tipo:"$tipo", }, total:{$sum:1} } }, {$group: { _id:"$_id.codigo", tipos: { $push: { tipo:"$_id.tipo", total:"$total" } }, totalGeneral:{$sum:"$total"} } } ]); 
0
source share

All Articles