Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Convert the data structure of a column in mongo db and store it in another column?

There are 3 million rows in mongo db
I want to create a 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 resulted in, This is not I want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading