使用另一个字段作为值将计算字段添加到每个数组元素

Add computed field to each array element using another field as value

结构:

"entity": [
    {
        "_id": {
            "$oid": "5bbf6e6d69a634eeb5a32a0e"
        },
        "Extension Id": "PR00027173",
        "Files": [
            {
                "Locale": "en_WW",
                "FileExtension": "ai",
                "Number": []
            },
            {
                "Locale": "sv_SE",
                "Type": "Technical drawing",
                "FileExtension": "eps",
                "Number": []
            }
        ]
    },
    {
        "_id": {
            "$oid": "5bbf6e6d69a634eeb5a32b7c"
        },
        "Extension Id": "PR00027174",
        "Files": [
            {
                "Locale": "en_WW",
                "FileExtension": "ai",
                "Number": []
            },
            {
                "Locale": "sv_SE",
                "Type": "Technical drawing",
                "FileExtension": "eps",
                "Number": []
            }
        ]
    }
]

我想在我的文件字段中的每个数组元素中添加计算字段(数字),并将其值设置为同一元素(即类型)中的其他字段。 我已经尝试过使用聚合框架,但每次我设置值时它都会从整个数组中获取所有值,即:

"Files": [
            {
                "Locale": "en_WW",
                "FileExtension": "ai",
                "Number": [
                    "ai",
                    "eps"
                ]
            },
            {
                "Locale": "sv_SE",
                "Type": "Technical drawing",
                "FileExtension": "eps",
                "Number": [                        
                    "ai",
                    "eps"
                ]
            }
]

是否可以将新字段 Number 值设置为 FileExtension,但只能来自同一元素而不是整个数组? 这就是我的总体预测:

  ["projection"]=> array(1) {
["Files.Number"]=>
string(29) "$Files.FileExtension"}}

这对于标准投影是不可能的,因为它是一个数组。您必须使用数组运算符 $map 来设置数组元素。

类似

db.collection.aggregate([
  ...other stages..
  {"$addFields":{
      "Files":{
        "$map":{
         "input":"$Files",
         "in":{
             "Locale": "$$this.Locale",
             "FileExtension": "$$this.FileExtension",
             "Number":"$$this.FileExtension"
          }
        }
      }
   }}
])