Home > Net >  Add field to each object of an array based on other field
Add field to each object of an array based on other field

Time:04-28

I have the following Array of data:

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

What I need is to add the correspondent value to each on of attr1 objects based on index. So the result would be:

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

I wonder if that possible using aggregation $addFields in MongoDB

CodePudding user response:

You can use $zip

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

Here is the Mongo playground for your reference.

CodePudding user response:

Query

  • query works if arrays same size
  • ziparray to make [[member1_1 member2_1], ....]
  • map to merge member1_1,member2_1 to a document

Playmongo

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