how can I rename field name in MongoDB?
I want to replace all the field names that start with $ to &.
Thanks!
how can I rename field name in MongoDB?
I want to replace all the field names that start with $ to &.
Thanks!
I saw some link and make a proper solution for you problem
First you need to get your all column, you could do this with MapReduce:
mr = db.runCommand({
"mapreduce" : "my_collection",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "my_collection" + "_keys"
});
Then run distinct on the resulting collection so as to find all the keys:
columns = db[mr.result].distinct("_id")
And rename the all matching columns
columns.forEach(function(columnName) {
if (columnName.indexOf('$') == 0) {
var newColumnName = columnName.replace('$', '&');
rename_query = { '$rename': {} };
rename_query['$rename'][columnName] = newColumnName;
db.my_collection.updateMany({}, rename_query)
}
})
Reference link are