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

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'] ) ) ) );
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮