【问题标题】:Array Transformation to object in mongoDB数组转换为mongoDB中的对象
【发布时间】:2021-09-14 06:33:18
【问题描述】:

说明:需要将Array转换为对象,在一个对象中包含学生XYZtotalmathmath_teach的信息。将预期输出视为一个文档。

文档 1:

{
  "students": [
    "X",
    "Y",
    "Z"
  ],
  "total": [
    150,
    200,
    100
  ],
  "math": [
    "A",
    "A+",
    "B+"
  ],
  "math_teach": [
    "A",
    "B",
    "C"
  ]

}

预期输出:

{
"total_students" : 3,
  "X" :{
    "total" : 150,
    "math" : "A",
    "math_teach" : "A"
  },
  "Y":{
    "total" : 200,
    "math" : "A+",
    "math_teach" : "B"
  },
  "Z" : {
    "total" : 100,
    "math" : "B+",
    "math_teach" : "C"
  }

}

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:
    • $size 获取 students 数组中的总元素
    • $map 迭代 students 数组的循环
    • $indexOfArraystudents 数组中获取当前学生索引
    • $arrayElemAt 从特定数组中获取上面的索引元素,例如totalmath
    • $arrayToObject将上面的对象键值数组结果转换为对象
    db.collection.aggregate([
      {
        $project: {
          total_students: { $size: "$students" },
          students: {
            $arrayToObject: {
              $map: {
                input: "$students",
                in: {
                  k: "$$this",
                  v: {
                    total: {
                      $arrayElemAt: [
                        "$total",
                        { $indexOfArray: ["$students", "$$this"] }
                      ]
                    },
                    math: {
                      $arrayElemAt: [
                        "$math",
                        { $indexOfArray: ["$students", "$$this"] }
                      ]
                    },
                    math_teach: {
                      $arrayElemAt: [
                        "$math_teach",
                        { $indexOfArray: ["$students", "$$this"] }
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2021-03-11
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2021-09-27
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多