Skip to content
Advertisement

Mongo db array of images change schema

I have an array of images in mongodb and I am trying to change the schema of the array. Right now the images are stored like bellow

JavaScript

And the final output I want is like bellow.

JavaScript

How can I do this in mongosh?

Is it easier to do this as a Python Array and then import back to mongodb? Thank you for your time!

Advertisement

Answer

Since mongoDB version 4.2+ you can do from mongosh as follow:

JavaScript

Explained:

  1. Replace via addFields the array x(we assume here the array field key is x) in your document with array of objects in the new format(using $indexOfArray to generate the content of the new “index” field.
  2. Add {multi:true} to update all documents in the collection

Playground

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement