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

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建