MongoDB 聚合 - 将对象中字段的值分配给自定义字段

MongoDB Aggregation - Assign a value of a field in an object to a custom field

给定以下数据结构:

[
  {
    "body": {
      "Fields": [
        {
          "Name": "description",
          "Value": "Some text"
        },
        {
          "Name": "size",
          "Value": "40"
        }
      ]
    }
  }
]

我需要获得以下输出,其中包含从 'Name' 字段中提取的键和由“值”字段提取的值:

[
  {
    "description": "Some text",
    "size": "40"
  }
]

能否请您提供我的想法? 我最终过滤了必需的元素,但不知道如何提取值并将它们分配给键。我目前拥有的:

db.collection.aggregate([
  {
    "$project": {
      "description": {
        "$filter": {
          "input": "$body.Fields",
          "as": "bfields",
          "cond": {
            "$eq": [
              "$$bfields.Name",
              "description"
            ]
          }
        }
      },
      "size": {
        "$filter": {
          "input": "$body.Fields",
          "as": "bfields",
          "cond": {
            "$eq": [
              "$$bfields.Name",
              "size"
            ]
          }
        }
      }
    }
  }
])

它产生:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "description": [
      {
        "Name": "description",
        "Value": "Some text"
      }
    ],
    "size": [
      {
        "Name": "size",
        "Value": "40"
      }
    ]
  }
]
 db.collection.aggregate([
 {
  $addFields: {
  body: {
    $map: {
      input: "$body.Fields",
      as: "fi",
      in: {
        k: "$$fi.Name",
        v: "$$fi.Value"
      }
    }
  }
}
},
{
 "$addFields": {
  "body": {
    "$arrayToObject": "$body"
   }
  }
 },
 {
  $project: {
  description: "$body.description",
  size: "$body.size",
  _id: 0
  }
 }
])

解释:

  1. 使用$map将键重命名为适合$arrayToObject的k,v
  2. 使用 $arrayToObject(魔术)将数组转换为对象
  3. $project 精确到所需的输出

playground