Canovice
Canovice

Reputation: 10243

Change fullName to firstName, lastName in MongoDB

enter image description here

We've updated our User collection to have firstName, lastName as 2 keys instead of fullName, but we have over 400 users that are currently created as fullName. I can use the MongoDB Atlas UI to manually create 400 sets of firstName, lastName keys, but that will take forever.

Can I use the mongo shell to (a) split the fullName by space, and (b) set the first name to the first value in the split array (everything before 1st space), and (c) set the last name to everything after the 1st space in the split array. John Smith would get split into John and Smith, and John Smith Jr. would get split into John and Smith Jr.. Is this possible to do in the mongo shell?

Upvotes: 0

Views: 829

Answers (2)

pbotas
pbotas

Reputation: 389

Improving a little bit on Tuchar's answer to actually put the remainder names in the last name, and also not use the deprecated .save():

db.User.find({}).forEach(function(doc) {
  if (doc.fullName && doc.fullName.split) {
    const parts = doc.fullName.split(' ');
    db.User.updateOne({_id: doc._id}, {$set: {
      firstName: parts.shift(1),
      lastName: parts.join(' ')
    }});
  }
});

Upvotes: 0

Use mongo shell to perform this one time activity

db.User.find({}).forEach(function(doc) { // loop over all the records
    if (doc.fullName && doc.fullName.split) {
        var name = doc.fullName.split(' ');
        if (name && name.length) {
            doc.firstName = name[0];
            if (name[1]) doc.lastName = name[1];
            // delete doc.fullName;
            db.User.save(doc); // save back the record
        }
    }
});

Upvotes: 2

Related Questions