Mongo Playground

Configuration

[{"_id":"1","title":"Vanella Icream","contain":"sugar","details":[{"flavour":"Vanella"},{"weight":"10KG"},{"sugar":"15KG"}]},{"_id":"2","title":"Pretzels","contain":"salt","details":[{"flavour":"Wheat"},{"weight":"10KG"},{"sugar":"15KG"}]},{"_id":"3","title":"Rasmalai Icream","contain":"sugar","details":[{"flavour":"Vanella"},{"weight":"15KG"},{"sugar":"12KG"}]},{"_id":"4","title":"Vanella Icream","contain":"sugar","details":[{"flavour":"Vanella"},{"weight":"15KG"},{"sugar":"12KG"}]}]

Query

db.collection.aggregate([{$unwind:"$details"},{$project:{details:{$objectToArray:"$details"}}},{$unwind:"$details"},{$group:{_id:{"k":"$details.k","v":"$details.v"},count:{$sum:1},label:{$last:"$details.k"}}},{"$group":{"_id":"$label",label:{"$last":"anchor"},details:{"$push":{"k":"$_id.v","v":"$count"}}}},{$project:{label:"$label",details:{$arrayToObject:"$details"}}},{"$group":{"_id":"$label",details:{"$push":{"k":"$_id","v":"$details"}}}},{$project:{_id:0,details:{$arrayToObject:"$details"}}},])

Result