I have the Mongo documents with the following structure:
{
"id" : 123,
"source" : "abc",
"media" : [
{
"index_num" : 0,
"media_url" : "some url"
},
{
"index_num" : 1,
"media_url" : "some url"
},
{
"index_num" : 2,
"media_url" : "some url"
}
]
}
The media field is an array. How can I convert the media array type field into the object type by adding a new field called num_images along with the existing array like below
{
"id" : 123,
"source" : "abc",
"media" : {
"media_info" : [
{
"index_num" : 0,
"media_url" : "some url"
},
{
"index_num" : 1,
"media_url" : "some url"
},
{
"index_num" : 2,
"media_url" : "some url"
}
],
"num_images" : 3
}
}
The value for num_images should be the size of the media_info array.
I tried multiple ways by using $arrayToObject, $addFields but none of them worked properly due to syntax errors and some other errors.
Could someone please help? I am new to Mongo and JS.