请帮助获得计数领域的总计

时间:2015-07-25 03:28:34

标签: mongodb

考虑以下查询。我怎样才能获得总计数。我尝试了不同的$ group而没有成功。

db.getCollection('customers').aggregate([
    { $match : { "status" : "Closed" } },
    { $unwind: "$lines" },
    { $match : { "lines.status" : "Closed" } },
    { $match : { "lines.deliveryMethod" : "Tech Delivers" } },
    { $group : {
      _id:{activityNumber:"$activityNumber",techid:"$techid",label: "$lines.product",date: {$substr: [ "$date", 0, 10 ]}},
      values: { $push:  
          { date: {$substr: [ "$date", 0, 10 ]} }
      },
      count: { $sum: 1 }
    }},
    { $group : {
      _id:"$_id.label",
      values : {
        $push : { date : "$_id.date", activityNumber:"$_id.activityNumber",techid:"$_id.techid",count : "$count"}
      }
    }
    },
    { $project : {
      _id : 0,
      key:"$_id",
      values:1,
      count:1
    }
    },{ $sort : { key : 1} }
  ])

这是我当前的输出

{
    "values": [
        {
            "date": "2015-05-18",
            "activityNumber": "1234124",
            "techid": "123121",
            "count": 1
        },
        {
            "date": "2015-05-19",
            "activityNumber": "5674567",
            "techid": "123124",
            "count": 1
        },
        {
            "date": "2015-05-18",
            "activityNumber": "67856785",
            "techid": "112341",
            "count": 5
        }
    ],
    "key": "SOME KEY"
}

以下是想要的结果。

{
        "values": [
            {
                "date": "2015-05-18",
                "activityNumber": "1234124",
                "techid": "123121",
                "count": 1
            },
            {
                "date": "2015-05-19",
                "activityNumber": "5674567",
                "techid": "123124",
                "count": 1
            },
            {
                "date": "2015-05-18",
                "activityNumber": "67856785",
                "techid": "112341",
                "count": 5
            }
        ],
        "key": "SOME KEY",
        "total": 7
    } 

提前感谢您的帮助

1 个答案:

答案 0 :(得分:2)

希望在发布问题之前我会稍微努力一下。但这是答案,以防将来帮助任何人。

db.getCollection('customers').aggregate([
    { $match : { "status" : "Closed" } },
    { $unwind: "$lines" },
    { $match : { "lines.status" : "Closed" } },
    { $match : { "lines.deliveryMethod" : "Tech Delivers" } },
    { $group : {
      _id:{activityNumber:"$activityNumber",techid:"$techid",label: "$lines.product",date: {$substr: [ "$date", 0, 10 ]}},
      values: { $push:  
          { date: {$substr: [ "$date", 0, 10 ]} }
      },
      count: { $sum: 1 }
    }},
    { $group : {
      _id:"$_id.label",
      values : {
        $push : { date : "$_id.date", activityNumber:"$_id.activityNumber",techid:"$_id.techid",count : "$count"}
      },total:{$sum:"$count"}
    }
    },
    { $project : {
      _id : 0,
      key:"$_id",
      values:1,
      total:1,
      count:1
    }
    },{ $sort : { key : 1} }
  ])