2

I was a bit dumb and created a collection in MongoDB with spaces in the key names:

{
        "_id" : ObjectId("5065f84d00ea10c01e00003f"),
        "DateTime" : ISODate("2012-09-27T15:19:00Z"),
        "Port Name" : "CL3-J",
        "Port Number" : "40",
        "Avg I/O /sec" : "2024.0",
        "array_serial" : "xxxxx"
}

I'm trying to define a function on the mongo shell to rename them:

var metricNames = ["Processor Busy %",
                      "Avg I/O /sec",    
                      "Avg Xfer /sec"];


var renameFields = function(collection) {
  var record = db[collection].findOne({});
  var myMetric;

  for (var key in record) {
    if(metricNames.indexOf(key) !== -1){
      myMetric = metricNames[metricNames.indexOf(key)];
      print(myMetric);
      break;
    } else {
      continue;
    }
  }

  db[collection].update( { }, { $rename : { 
                                            'DateTime'    : 'datetime',
                                            'Port Name'        : 'port_name',
                                            'Port Number'      : 'port_number',
                                            'Adaptor ID'       : 'adaptor_id',
                                            'Processor ID'     : 'processor_id',
                                            'Processor Type'   : 'processor_type',
                                             myMetric          : 'metric' } }, false, true );

}

Depending on the collection specified the metric could possibly be one of the three... the issue is that all of the specified fields except the 'myMetric' one are being renamed correctly, the metric field is remaining the original field with spaces.

Any ideas?


...an update.

It seems that collections with the "Avg Xfer /sec" metric are properly renamed to "metric" but collections with "Avg I/O /sec" or "Processor Busy %" are not. I'm not entirely sure why that would be.

Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
Chris Matta
  • 3,263
  • 3
  • 35
  • 48
  • What's the problem with spaces in the key names? – cirrus Oct 01 '12 at 20:30
  • For my particular usage having collections with the same schema has reduced the amount of code I have to do on the front-end. I can create a generic model if they all have a 'metric' instead of different keys. – Chris Matta Oct 01 '12 at 20:50

1 Answers1

3

It's because the rename update is looking for a property named 'myMetric' to rename and not one named myMetric's value. You need to build up your rename object programmatically:

var rename = { 
  'DateTime'    : 'datetime',
  'Port Name'        : 'port_name',
  'Port Number'      : 'port_number',
  'Adaptor ID'       : 'adaptor_id',
  'Processor ID'     : 'processor_id',
  'Processor Type'   : 'processor_type'
};
rename[myMetric] = 'metric';
db[collection].update( { }, { $rename : rename }, false, true );
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471