在 MongoDB 中添加总计 sub-totals

Add a total to aggregated sub-totals in MongoDB

假设我的 MongoDB collection 中有这样的文档:

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

我可以使用显示 sub-totals 的聚合创建管道视图,即

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

这导致:

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

但是如何在此视图中添加总计,即

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

查询 1

  • 要计数的组
  • 在一个额外的文档中与相同的集合合并,使用管道添加总计数

Test code here

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

查询2

  • 没有 $union for MongoDB < 4.4
  • 分组并计数
  • 按 null 分组并收集文档,以及总计数
  • 将额外文档添加到 docs 数组
  • 展开并替换 root 以恢复结构

Test code here

aggregate(
[{"$group":{"_id":"$name", "count":{"$sum":1}}},
 {"$group":
  {"_id":null, "docs":{"$push":"$$ROOT"}, "total":{"$sum":"$count"}}},
 {"$project":
  {"docs":
   {"$concatArrays":["$docs", [{"_id":"ALL", "count":"$total"}]]}}},
 {"$unwind":"$docs"},
 {"$replaceRoot":{"newRoot":"$docs"}}])

试试这个:

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

Mongo Playground