Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change capital letters in mongo to camel casing?

Tags:

mongodb

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',
  ...
}
like image 224
bender Avatar asked Oct 28 '25 04:10

bender


1 Answers

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) } }
    );
});
like image 126
Sourabh Bhagat Avatar answered Oct 29 '25 22:10

Sourabh Bhagat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!