2017-01-13

MongoDB - How to rename a field within an array of objects/sub-documents?

db.collection_name.find({

// Filter to only work on documents that contain the array field
"parent_field.child_old_field_name": { $exists : 1 }

}).forEach(
    function( doc ){

    // For each object in the current document's array
        for( i=0; i < parent_field.length; ++i ) {

            // Create the new field
            doc.parent_field[i].child_new_field_name = doc.parent_field[i].child_old_field_name;

            // Delete the old field
            delete doc.parent_field[i].child_old_field_name;
        }

        // Update the document
        db.collection_name.update(
        // Only the current document
        { _id : doc._id }
        // The updated document (as per the statements in the above "for" loop)
        , doc 
        );
    }
);



// This is how the collection that fits the example looks like:
{
    "_id" : "bs2XTNDYLSrp9Ae9m"
    , "parent_field" : [ 
        {
            "child_old_field_name" : "any value" 
        }
        , {
            "child_old_field_name" : "Any other value"
        }        
    ]
}

1 comment:

  1. excellent code, works like a charm, thanks
    ahh, but it was missing a word.

    // For each object in the current document's array
    for( i=0; i < doc.parent_field.length; ++i ) {

    // Create the new field....

    ReplyDelete