Database

[{"key":1,name:"steve",downloads:[{country:"HKG"},{country:"HKG"},{country:"HKG"},{country:"HKG"},{country:"JPFN"},]},{"key":2,name:"elon",downloads:[{country:"SSGD"},{country:"JPN"},{country:"SGD"},{country:"HKG"},{country:"JPN"},]},{"key":4,name:"mark",downloads:[{country:"USA"},{country:"USA"},{country:"USA"},{country:"USA"},{country:"USA"},{country:"CHN"},]}]

Query

/**Do not like this lengthy query which uses map and filter*Would be great if i could use a single reduce*Desired Output*{* name : 'steve',* TopCountry : HKG* }*/db.collection.aggregate([{$addFields:{TopCountry:{$map:{input:{$setUnion:"$downloads"},/** unique elements of flags array*/as:"f",in:{country:"$$f.country",count:{$size:{$filter:{input:"$downloads",cond:{$eq:["$$this","$$f"]}},}},},},},},},{$project:{_id:0,name:1,TopCountry:{$max:"$TopCountry.count"}}}])

Result