MongoDB按字段分组,带条件统计

MongoDB Group by field, count it with condition

我想为一批货计算不同的hu。所以我写了这个查询,但我如何按发货计算不同的 hu 组?

我的查询:

db.eventstranslated.aggregate([
  { "$group": {
    "_id": "$IdShipment",
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": null,
    "ship": {
      "$push": {
        "shipment": "$_id",
        "count": "$count"
      }
    }
  }},
  { "$project": { "_id": 0 }}
])

结果:

{ shipment: A01, count: 1 },
{ shipment: A02, count: 1 },

预期输出:

{shipment: A01, count: 2 }
{shipment: A02, count: 1 }

我的collection:

{
  _id: 1,
  IdShipment: "A01",
  hu: "C111"
},
{
  _id: 2,
  IdShipment: "A01",
  hu: "C112"
},
{
  _id: 3,
  IdShipment: "A02",
  hu: "D111"
},
{
  _id: 4,
  IdShipment: "A02",
  hu: "D111"
}

您可以像这样使用两个 $group 阶段:

第一个 $group 有一个复合键来获取所有不同的选项,第二个 $group 是只获取不同的 IdShipment.

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        "IdShipment": "$IdShipment",
        "hu": "$hu"
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.IdShipment",
      "count": {
        "$sum": 1
      }
    }
  }
])

示例here

也可以用$project输出你想要的名字。示例 here