1

how can I rename field name in MongoDB?

I want to replace all the field names that start with $ to &.

Thanks!

ashwin
  • 332
  • 2
  • 16

1 Answers1

0

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

MongoDB Get names of all keys in collection

MongoDB $rename javascript variable for key name

Community
  • 1
  • 1
Gaurav Kumar Singh
  • 1,550
  • 3
  • 11
  • 31
  • Actually, I don't know the field name, all I know is there are fields which start with $. is there any like operator which we can use? – ashwin Mar 08 '17 at 19:44
  • I have updated the answer according to your requerment – Gaurav Kumar Singh Mar 08 '17 at 20:38
  • Thanks @gaurav, i have another issue few field names are in array. – ashwin Mar 08 '17 at 22:12
  • below is sample document { "_id" : ObjectId("123"), "op" : "command", "ns" : "test.test", "command" : { "aggregate" : "test", "pipeline" : [ { "$match" : { "identifier" : "U1", "audience" : /^agent$/i } }, { "$limit" : 1 } ], – ashwin Mar 09 '17 at 22:30