Calculate percentage within a group in mongodb using aggregation pipeline. Suppose I have a collection like shown below with some documents.
[{
"Name":"xyz" ,
"Area":"London",
"Sex":"Male"
},
{
"Name":"aaa" ,
"Area":"London",
"Sex":"Female"
},
{
"Name":"bbb" ,
"Area":"London",
"Sex":"Female"
},
{
"Name":"ccc" ,
"Area":"London",
"Sex":"Female"
},
{
"Name":"abc" ,
"Area":"Chile",
"Sex":"Female"
},
{
"Name":"xxx" ,
"Area":"Chile",
"Sex":"Male"
}
]
I want percentage of male and female by each area. Expected output should be something like.
[
{
_id {
area : 'London', Sex:'Male'
},
percentage: 25
},
{
_id {
area : 'London', Sex:'Female'
},
percentage: 75
},
{
_id {
area : 'Chile', Sex:'Female'
},
percentage: 50
},
{
_id {
area : 'Chile', Sex:'Male'
},
percentage: 50
}
]