将对象数组分组并在mongodb中获取计数

dfuffjeb  于 2023-06-05  发布在  Go
关注(0)|答案(1)|浏览(145)

我有一个对象数组:

[
  {
    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,但没有得到预期的结果。需要一些有价值的帮助。

ffscu2ro

ffscu2ro1#

类似于previous question
分组时,可以根据字段的值有条件地求和
1.基于categorysubCategory值创建key字段
1.按键分组,并根据providedBy的值有条件地添加到providedByDoctorprovidedByNure
1.分组为单个medicationDetails阵列

db.collection.aggregate([
  { 
   $project: {
      providedBy: "$medicationDetails.providedBy",
      key: { $cond: [ { $eq: [ "$medicationDetails.subCategory", "" ] }, "$medicationDetails.category", "$medicationDetails.subCategory" ] }
    } 
  },
  {
    $group: { 
      _id: "$key",
      providedByDoctor: { $sum: { $cond: [ { $eq: [ "$providedBy", "Doctor" ] }, 1, 0 ] } },
      providedByNurse: { $sum: { $cond: [ { $eq: [ "$providedBy", "Nurse" ] }, 1, 0 ] } } }
  },
  { $group: { _id: null, medicationDetails: { $push: { name: "$_id", providedByDoctorCount: "$providedByDoctor", providedByNurseCount: "$providedByNurse" } } } },
  { $unset: "_id" }
])

playground

相关问题