0

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.

1 Answer 1

1
  1. $set - Create new_media field with an object contains media_info array and num_images field.

  2. $set - Replace media value with new_media.

  3. $unset - Remove new_media field.

db.collection.aggregate([
  {
    $set: {
      "new_media": {
        "media_info": "$media",
        "num_images": {
          $size: "$media"
        }
      }
    }
  },
  {
    $set: {
      media: "$new_media"
    }
  },
  {
    $unset: "new_media"
  }
])

Demo @ Mongo Playground

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, @Yong Shun I just realised the aggregate pipeline only shows the data but does not commit it (or alter existing data).. How do I commit this modified document to the collection
You can update with aggregation pipeline. Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.