Home > database >  Add a total to aggregated sub-totals in MongoDB
Add a total to aggregated sub-totals in MongoDB

Time:01-05

Let's say I have documents in my MongoDB collection that look like this:

{ name: "X", ...}
{ name: "Y", ...}
{ name: "X", ...}
{ name: "X", ...}

I can create a pipeline view using aggregation that shows sub-totals i.e.

$group: {
  _id: '$name',
  count: {
    $sum: 1
  }
}

which results in:

{ _id: "X",
  count: 3 },
{ _id: "Y",
  count: 1}

but how do I add a total in this view i.e.

{ _id: "X",
  count: 3 },
{ _id: "Y",
  count: 1},
{_id: "ALL",
 count: 4}

CodePudding user response:

Query

  • group to count
  • union with the same collection, with pipeline to add the total count, in one extra document

Test code here

coll1.aggregate(
[{"$group":{"_id":"$name", "count":{"$sum":1}}},
 {"$unionWith":
  {"coll":"coll1",
   "pipeline":[{"$group":{"_id":"ALL", "count":{"$sum":1}}}]}}])

CodePudding user response:

Try this one:

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      count: { $count: {} }
    }
  },
  {
    $unionWith: {
      coll: "collection",
      pipeline: [
        {
          $group: {
            _id: "ALL",
            count: { $count: {} }
          }
        }
      ]
    }
  }
])

Mongo Playground

  •  Tags:  
  • Related