duanqinqian5299 2012-02-25 11:31
浏览 454
已采纳

Mongodb:将字段更改为数组

Lets say we have a document like this

{
    "_id" : "1234",
    "Data" : {
         "Name" : "Pythagoras",
         "Like" : "Math"
}

And we changed over mind and want to push more things to Data->Like so it looks like;

{
    "_id" : "1234",
    "Data" : {
         "Name" : "Pythagoras",
         "Like" : ["Math", "Science"]
}

All the atomic operators like $push, $pushAll and $addToSet works just when Data->Like already is an array.

I´m using the php-driver. In this example there is no meaning to not set the Data->Like to an array at the beginning but it does not work like that in my code ;(

Hope you can help me and sorry for my bad English ;) Thanks!

  • 写回答

1条回答 默认 最新

  • dongqian9567 2012-02-25 12:27
    关注

    You'll have to iterate over all your documents and change the value to an array. For example, you can do that with:

    $m = new Mongo();
    $c = $m->yourdbname->yourcollectionname;
    
    foreach ( $c->find() as $r )
    {
        if ( !is_array( $r['Data']['Like'] ) )
        {
            $c->update( array( '_id' => $r['_id'] ), array( '$set' => array( 'data.like' => array( $r['data']['like'] ) ) ) );
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问