如何按嵌套数组对象中的元素分组

时间:2019-05-07 18:37:45

标签: mongodb aggregation-framework

我有嵌套的数组和对象。我想分别过滤每种药物。如文件:

{   
    person: "X",
    treatment: [
        {
            id: 1,
            medication: [
                {
                    name: "A"
                },
                {
                    name: "B"
                }
            ]
        },
        {
            id: 2,
            medication: [
                {
                    name: "A"
                },
                {
                    name: "C"
                }
            ]
        }
    ]
},
{
    person: "Y",
    treatment: [
        {
            id: 1,
            medication: [
                {
                    name: "B"
                },
                {
                    name: "C"
                }
            ]
        }
    ]
}

我怎样才能得到一份顶级药物清单?像这样:A:2,B:2,C:2

1 个答案:

答案 0 :(得分:0)

您需要使用$unwind来为数组中的每个元素输出一个文档。由于存在嵌套数组,因此您需要两次应用$unwind

例如名为medicine的集合:

db.medicine.aggregate([
  { 
    $unwind : "$treatment"
  },
  { 
    $unwind : "$treatment.medication"
  },
  {
    $group : { _id : "$treatment.medication.name", total: { $sum: 1 } }
  },
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: {
          $let: {
            vars: { data: [ { k: "$_id", v: "$total" } ] },
            in: "$$data"
          }
        }
      }
    }
  } 
])

输出:

{ "C" : 2 }
{ "B" : 2 }
{ "A" : 2 }

请注意,在展开嵌套数组时,如果数组很大,则可以生成许多文档,因此您可能需要检查这个问题Consequences of using $unwind on nested arrays?

相关问题