gh0st
gh0st

Reputation: 1714

Refactor Name in MongoDB Document

In my current mongo collection my objects are stored such as

{
    _id: '....',
    name: 'Thomas Jefferson',
    date: '12/1/2016'
}

Some are stored such as

{
    _id: '....',
    name: 'FRANKLIN, BENJAMIN',
    date: '12/1/2016'
}

But now I must rewrite/refactor my documents so that they are of the format

{
    _id: '....',
    name: {
        first: 'BENJAMIN',
        last: 'FRANKLIN'
    },
    date: '12/1/2016'
},
{
    _id: '....',
    name: {
        first: 'Thomas',
        last: 'Jefferson'
    },
    date: '12/1/2016'
}

I know there's not a single command I can accomplish both cases with but is there one in which I can accomplish the LASTNAME, FIRSTNAME case?

Upvotes: 0

Views: 255

Answers (1)

Julien TASSIN
Julien TASSIN

Reputation: 5212

you can do it with find().foreach in the shell.

Before

db.users.find().pretty()
{
        "_id" : ObjectId("58ffc291055ee5ec5334d97b"),
        "name" : "FRANKLIN, BENJAMIN",
        "date" : "12/1/2016"
}
{
        "_id" : ObjectId("58ffc298055ee5ec5334d97c"),
        "name" : "Thomas Jefferson",
        "date" : "12/1/2016"
}

Query

// {name: {$type: 'string'}} will filter on records with name of type string
db.users.find({name: {$type: 'string'}}).forEach(function(item) {
  if (item.name) {
    var lastname = item.name.split(' ')[0].replace(',', '');
    var firstname = item.name.split(' ')[1];
    db.users.update(
      {_id: item._id}, 
      {$set: {lastname: lastname, firstname: firstname}}
    )
  }
})

After

db.users.find().pretty()
{
        "_id" : ObjectId("58ffc291055ee5ec5334d97b"),
        "name" : "FRANKLIN, BENJAMIN",
        "date" : "12/1/2016",
        "lastname" : "FRANKLIN",
        "firstname" : "BENJAMIN"
}
{
        "_id" : ObjectId("58ffc298055ee5ec5334d97c"),
        "name" : "Thomas Jefferson",
        "date" : "12/1/2016",
        "lastname" : "Thomas",
        "firstname" : "Jefferson"
}

Upvotes: 2

Related Questions