Vous pouvez essayer la requête ci-dessous :
db.collection.aggregate([
/** Group all docs based on flightNum & status & count no.of occurances */
{
$group: {
_id: {
flightNum: "$flightNum",
status: "$status"
},
count: {
$sum: 1
}
}
},
/** Group on flightNum & push an objects with key as status & value as count */
{
$group: {
_id: "$_id.flightNum",
status: {
$push: {
k: "$_id.status",
v: "$count"
}
}
}
},
/** Recreate status field as an object of key:value pairs from an array of objects */
{
$addFields: {
status: {
$arrayToObject: "$status"
}
}
},
/** add flightNum inside status object */
{
$addFields: {
"status.flightNum": "$_id"
}
},
/** Replace status field as new root for each doc in coll */
{
$replaceRoot: {
newRoot: "$status"
}
}
])
Tester : MongoDB-Playground