Renaming fields of objects inside array's in MongoDB

Bharat Kalluri / 2020-09-30

Ref

db.collection_name.find({ 'array_of_objects_field.0.old_name': { $exists: 1 } }).forEach(function(item)
{
for(i = 0; i != array_of_objects_field.length; ++i)
{
item.array_of_objects_field[i].new_name = item.array_of_objects_field[i].old_name;
delete item.array_of_objects_field[i].old_name;
}
db.collection_name.update({_id: item._id}, item);
});

Subscribe to the newsletter

Spotify album cover

NowReading logDashboardUses