4

I have a collection named User, which contains the the fields firstName and secondName. But the data is in capital letters.

{
  firstName: 'FIDO',
  secondName: 'JOHN',
  ...
}

I wanted to know whether it is possible to make the field to camel case.

{
  firstName: 'Fido',
  secondName: 'John',
  ...
}
bender
  • 369
  • 1
  • 4
  • 9

2 Answers2

5

You can use a helper function to get your desired answer.

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
        return word.replace(word[0], word[0].toUpperCase());
    }).join(' ');
}

db.User.find().forEach(function(doc){
    db.User.update(
        { "_id": doc._id },
        { "$set": { "firstName": titleCase(doc.firstName) } }
    );
});
Sourabh Bhagat
  • 1,691
  • 17
  • 20
0

Run an update operation with aggregate pipeline as follows:

const titleCase = key => ({
   $concat: [
      { $toUpper: { $substrCP: [`$${key}`,0,1] } },
      { $toLower: {
            $substrCP: [
               `$${key}`, 
               1,
               { $subtract: [ { $strLenCP: `$${key}` }, 1 ] }
            ]
      } }
   ]
});
db.User.updateMany(
   {},
   [
      { $set: { 
         firstName: titleCase('firstName'),
         secondName: titleCase('secondName')
      } }
   ]
)

Mongo Playground

chridam
  • 100,957
  • 23
  • 236
  • 235