Home > front end >  MongoDB - Convert array of objects to object contains array and extra fields
MongoDB - Convert array of objects to object contains array and extra fields

Time:01-27

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.

CodePudding user response:

  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

  • Related