Change capital letters in mongo to camel casing?

2020-06-06 02:26发布

问题:

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',
  ...
}

回答1:

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) } }
    );
});


标签: mongodb