Search code examples
mongodbmongodb-querymongodb-update

MongoDB - How to convert the data structure of a column and store it in another column


There are 3 million rows in MongoDB. I want to create column B using column A.

A : [1,2,3,4]
// All level value is 1
B : [
  { key: 1, level: 1 },
  { key: 2, level: 1 },
  { key: 3, level: 1 },
  { key: 3, level: 1 },
];

What I have tried:

table.update_many({}, [
    {
        "$set": {
            "B": {"key" : "$A", "level" : 1}
        }
    }
])

But this result is not what I want.

B : {"sku_id" : [1,2,3,4], "level" : 1}

Is there any way to bulk update? Or do I need to update one row at a time?


Solution

  • You need to use $map to iterate each element in the A array and transform into a new array with documents.

    db.collection.update({},
    [
      {
        "$set": {
          "B": {
            $map: {
              input: "$A",
              in: {
                "key": "$$this",
                "level": 1
              }
            }
          }
        }
      }
    ])
    

    Demo @ Mongo Playground