skip to Main Content

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

2

Answers


  1. You can use $zip

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

    Here is the Mongo playground for your reference.

    Login or Signup to reply.
  2. 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]}]}}}}}])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search