使用mongodb的所有组的总计

时间:2018-10-21 22:39:08

标签: mongodb grouping aggregate

我做了这个聚合管道,我想添加一个包含所有Total的全局groups total的字段。

    { "$match": query },
    { "$sort": cursor.sort },
    { "$group": { 
      _id: { key:"$paymentFromId"},
      items: {
        $push: {
         _id:"$_id",
         value:"$value",
         transaction:"$transaction",
         paymentMethod:"$paymentMethod",
         createdAt:"$createdAt",
         ...
        }
      },
      count:{$sum:1},
      total:{$sum:"$value"}
    }}
    {
      //i want to get
      ...project groups , goupsTotal , groupsCount
    }
    ,{
      "$skip":cursor.skip
    },{
      "$limit":cursor.limit
    },
])

2 个答案:

答案 0 :(得分:0)

您需要使用$facet(可从MongoDB 3.4获得)在同一组文档上应用多个管道

第一个管道 :跳过并限制文档

第二个管道 :计算所有组的总数

  { "$match": query },
  { "$sort": cursor.sort },
  { "$group": { 
  _id: { key:"$paymentFromId"},
  items: {
    $push: "$$CURRENT"
  },
  count:{$sum:1},
  total:{$sum:"$value"}
    }
 },
 {
   $facet: {
      docs: [
        { $skip:cursor.skip },
        { $limit:cursor.limit }
     ],
      overall: [
       {$group: {
             _id: null, 
             groupsTotal: {$sum: '$total'}, 
             groupsCount:{ $sum: '$count'}
         }
      }
   ]
 }

最终输出将是

 {
    docs: [  .... ], // array of {_id, items, count, total}
    overall: {   } // object with properties groupsTotal, groupsCount
 }

PS:在第三管道阶段,我用$$CURRENT替换了这些项目,为了简化起见,它添加了整个文档,如果您需要自定义属性,请指定它们。

答案 1 :(得分:0)

我这样做,将$group结果投影到新字段doc$sum子总计中。

 {
  $project: {
      "doc": {
          "_id": "$_id",
          "total": "$total",
          "items":"$items",
          "count":"$count"
      }
  }
},{
  $group: {
      "_id": null,
      "globalTotal": {
          $sum: "$doc.total"
      },
      "result": {
          $push: "$doc"
      }
  }
},
{
  $project: {
      "result": 1,
      //paging "result": {$slice: [ "$result", cursor.skip,cursor.limit ] },
      "_id": 0,
      "globalTotal": 1
  }
}

输出

[
 { 
  globalTotal: 121500,
  result: [ [group1], [group2], [group3], ... ]
 }
]