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
["https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg","https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg","https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg"]
And the final output I want is like bellow.
[ { url: "https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg", index: "1" }, { url: "https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg", index: "2" }, { url: "https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg", index: "3" }, ]
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:
db.collection.update({}, [ { $addFields: { x: { "$map": { "input": "$x", "as": "y", "in": { url: "$$y", index: { $indexOfArray: [ "$x", "$$y" ] } } } } } } ], { multi: true })
Explained:
- 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.
- Add {multi:true} to update all documents in the collection