根据其他字段向数组的每个对象添加字段

Add field to each object of an array based on other field

我有以下数据数组:

    {
            _id: 5f5726ef7d475a61a95c5e0c,
            attributes: [
                {
                    values: [
                        { name: '1' }
                    ],
                },
                { 
                    values: [
                        { name: '2' }
                    ]
                }
            ],
            attr1: [
                { name: "Study Code" },
                { name: "Patient Study" }
            ]
    }

我需要的是根据索引为每个attr1对象添加对应的value。所以结果将是:

    {
            _id: 5f5726ef7d475a61a95c5e0c,
            attributes: [
                {
                    values: [
                        { name: '1' }
                    ],
                },
                { 
                    values: [
                        { name: '2' }
                    ]
                },
            ],
            attr1: [
                {
                    name: "Study Code",
                    values: [{ name: "1" }]
                },
                {
                    name: "Patient Study",
                    values: [{ name: "2" }]
                }
            ],
    }

我想知道是否可以在 MongoDB

中使用聚合 $addFields

您可以使用$zip

db.collection.aggregate([
  {
    "$project": {
      attributes: {
        "$zip": {
          "inputs": [
            "$attributes",
            "$attr1"
          ]
        }
      }
    }
  }
])

这里是Mongo playground供您参考。

查询

  • 如果数组大小相同,则查询有效
  • ziparray 制作 [[member1_1 member2_1], ....]
  • 映射以将 member1_1、member2_1 合并到文档

Playmongo

aggregate(
[{"$set": {"attr1": {"$zip": {"inputs": ["$attributes", "$attr1"]}}}},
 {"$set": 
   {"attr1": 
     {"$map": 
       {"input": "$attr1",
        "in": 
         {"$mergeObjects": 
           [{"$arrayElemAt": ["$$this", 1]},
             {"$arrayElemAt": ["$$this", 0]}]}}}}}])