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
x
2
1
["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"]
2
And the final output I want is like bellow.
JavaScript
1
18
18
1
[
2
{
3
url:
4
"https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg",
5
index: "1"
6
},
7
{
8
url:
9
"https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg",
10
index: "2"
11
},
12
{
13
url:
14
"https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg",
15
index: "3"
16
},
17
]
18
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
1
26
26
1
db.collection.update({},
2
[
3
{
4
$addFields: {
5
x: {
6
"$map": {
7
"input": "$x",
8
"as": "y",
9
"in": {
10
url: "$$y",
11
index: {
12
$indexOfArray: [
13
"$x",
14
"$$y"
15
]
16
}
17
}
18
}
19
}
20
}
21
}
22
],
23
{
24
multi: true
25
})
26
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