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"
}
我想为一批货计算不同的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"
}