【问题标题】:Group nested array to single array in mongodb在 mongodb 中将嵌套数组分组为单个数组
【发布时间】:2023-02-24 03:15:36
【问题描述】:

我有两个集合“免疫”和“学生”。每个学生都有两份免疫记录。只需要显示具有“缺陷”状态的免疫接种,因此我使用如下过滤器对某些条件进行了分组:

return this.immunization.aggregate([
  {
    $lookup: {
      from: 'students',
      foreignField: '_id',
      localField: 'studentId',
      as: 'studentData',
    },
  },
  {
    $unwind: '$studentData',
  },
  {
    $group: {
      _id: {
        studentNumber: '$studentData.studentNumber',
        studentName: '$studentData.name',
      },
      immunizationDetails: {
        $push: {
          $let: {
            vars: {
              immunizationDetails: {
                $filter: {
                  input: '$immunizationList',
                  as: 'item',
                  cond: {
                    $eq: ['$$item.status', 'Deficient'],
                  },
                },
              },
            },
            in: '$$immunizationDetails.name'
          },
        },
      },
    }
  },
  {
    $project: {
      _id: 0,
      studentDetails: '$_id',
      immunizationDetails: '$immunizationDetails'
    },
  }
]);

我得到这样的结果:

[
  {
    "studentDetails": {
      "studentNumber": 123,
      "studentName": "abc"
    },
    "immunizationDetails": [
      [
        "Rubella"
      ],
      [
        "PCV13",
        "Tdap"
      ]
    ]
  },
  {
    "studentDetails": {
      "studentNumber": 321,
      "studentName": "xyz"
    },
    "immunizationDetails": [
      [
        "Hepatitis B",
        "HIB"
      ],
      [
        "PCV13"
      ]
    ]
  }
]

但我需要将免疫详细信息放在一个数组中,如下所示:

[
  {
    "studentDetails": {
      "studentNumber": 123,
      "studentName": "abc"
    },
    "immunizationDetails": ["Rubella", "PCV13", "Tdap"] 
  },
  {
    "studentDetails": {
      "studentNumber": 321,
      "studentName": "xyz"
    },
    "immunizationDetails": ["Hepatitis B", "HIB", "PCV13"]
  }
]

需要某人的宝贵帮助。

【问题讨论】:

    标签: arrays mongodb aggregation


    【解决方案1】:

    只需再添加一个 $reduce 和 $concatArrays 即可使结果变平。

    db.collection.aggregate([
      {
        "$set": {
          "immunizationDetails": {
            "$reduce": {
              "input": "$immunizationDetails",
              "initialValue": [],
              "in": {
                "$concatArrays": [
                  "$$value",
                  "$$this"
                ]
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多