How to rename fields in array?

906 views
Skip to first unread message

Дима Прусский

unread,
Apr 18, 2018, 7:08:10 PM4/18/18
to mongodb-user
I have following structure of documents:
{
    "_id" : 12421,
    "first" : {
        "second" : {
            "someFields" : 31241,
            "third" : [ 
                {
                    "wrongFieldName" : {
                        "something" : 2134214
                    }
                }, 
                {
                    "wrongFieldName" : {
                        "something" : 23413
                    }
                }
            ]
        }
    }
}
I want to change all "wrongFieldName" to "rightFieldName":
{
    "_id" : 12421,
    "first" : {
        "second" : {
            "someFields" : 31241,
            "third" : [ 
                {
                    "rightFieldName" : {
                        "something" : 2134214
                    }
                }, 
                {
                    "rightFieldName" : {
                        "something" : 23413
                    }
                }
            ]
        }
    }
}
I tried to use $rename, but it was thrown an error, because needed fields are in array: 
The source field for $rename may not be dynamic: first.second.third.$.wrongFieldName

Chandraneel

unread,
Apr 24, 2018, 5:12:59 PM4/24/18
to mongodb-user
Worked using forEach:

db.collection.find({}).forEach(function(doc){
    for(var i=0;i<doc.first.second.third.length;i++){
        doc.first.second.third[i].correctFieldName=doc.first.second.third[i].wrongFieldName;
        delete doc.first.second.third[i].wrongFieldName;
        }
      db.collection.save(doc);
    });
Reply all
Reply to author
Forward
0 new messages