MongoDB文档中的重构名称

时间:2017-04-25 14:56:56

标签: mongodb

在我当前的mongo集合中,我的对象存储如

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

有些存储如

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

但是现在我必须重写/重构我的文档,使它们的格式为

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

我知道我没有一个命令可以完成这两个案例,但有一个命令可以完成 LASTNAME,FIRSTNAME 案例吗?

1 个答案:

答案 0 :(得分:2)

你可以在shell中使用find().foreach

<强>之前

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

<强>查询

// {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}}
    )
  }
})

<强>后

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"
}