我有一个对象数组:
[
{
medicationDetails: {
category: 'Asthma',
subCategory: '',
providedBy: 'Doctor'
}
},
{
medicationDetails: {
category: 'Diabetes',
subCategory: 'Oral',
providedBy: 'Nurse'
}
},
{
medicationDetails: {
category: 'Asthma',
subCategory: ''
providedBy: 'Doctor'
}
},
{
medicationDetails: {
category: 'Diabetes',
subCategory: 'Insulin',
providedBy: 'Doctor'
}
}
]
一些药物将有子类别,而一些则没有。
需要根据'category'、'sub-category'和'providedBy'进行分组,并像这样获取计数:
[
{
medicationDetails: [
{
name: 'Asthma',
providedByDoctorCount: 2,
providedByNurseCount: 0
},
{
name: 'Oral',
providedByDoctorCount: 0,
providedByNurseCount: 1
},
{
name: 'Insulin',
providedByDoctorCount: 1,
providedByNurseCount: 0
}
]
}
]
我尝试了$group和$count,但没有得到预期的结果。需要一些有价值的帮助。
1条答案
按热度按时间ffscu2ro1#
类似于previous question。
分组时,可以根据字段的值有条件地求和
1.基于
category
和subCategory
值创建key
字段1.按键分组,并根据
providedBy
的值有条件地添加到providedByDoctor
或providedByNure
1.分组为单个
medicationDetails
阵列playground