Hello @Georg_Bote, I have this aggregation which outputs the desired result.
db.collection.aggregate([
{
$unwind: "$flags"
},
{
$group: {
_id: "$flags",
count: { $sum: 1 },
regions: { $first: "$regions" },
doc: { $first: { id: "$id", requestcount: "$requestcount", bookingcount: "$bookingcount" } }
}},
{
$group: {
_id: null,
flags: { $push: { name: "$_id", count: "$count" }},
regions: { $first: "$regions" }, doc: { $first: "$doc" }
}},
{
$unwind: "$regions"
},
{
$group: {
_id: "$regions",
count: { $sum: 1 },
flags: { $first: "$flags" },
doc: { $first: "$doc" }
}},
{
$group: {
_id: null,
regions: { $push: { _id: "$_id", count: "$count" }},
flags: { $first: "$flags" },
doc: { $first: "$doc" }
}},
{
$project: {
_id: 0,
id: "$doc.id",
requestcount: "$doc.requestcount",
bookingcount: "$doc.bookingcount",
regions: 1,
flags: 1
}}
])
Note that it is possible that your aggregation’s $project is not required.