MongoDB nested group?

后端 未结 2 1630
终归单人心
终归单人心 2020-12-23 22:36

I\'m trying to implement a nested group query in mongodb and I\'m getting stuck trying to add the outer group by. Given the below (simplified) data document:



        
2条回答
  •  死守一世寂寞
    2020-12-23 23:27

    You will need two groups in this case. The first group generates a stream of documents with one document per term and category:

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

    A second group will then merge all documents with the same term into one, using the $push operator to merge the categories into an array:

     { $group : { 
          _id :  "$_id.category",
          terms: { 
              $push: { 
                  term:"$_id.term",
                  total:"$total"
              }
          }
       }
     }
    

提交回复
热议问题