MongoDB updating fields in nested array

后端 未结 3 2087
庸人自扰
庸人自扰 2020-12-06 13:46

MongoDB updating fields in nested array

How can I set \"play\" to \"play photo\" in the photos array?

I only know its _id.

\"_id\": ObjectId(         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 14:34

    Tonilin You Cant Update this type of array directly for this you need to find the index of that array in which you want to update like if you want to update name as play photo then you have to find the index of photos where name is play. For this I used this code like:

    $m = new Mongo();
    $db=$m->yourdatabase;
    //testarray is my collection name
    $result=$db->testarray->find();
    $index='';
    foreach($result as $res)
    {
        if(array_key_exists("albums",$res))
        {
            foreach($res['albums'] as $ralbum)
            {
                if(array_key_exists("photos",$ralbum))
                {
                    foreach($ralbum['photos'] as $k=>$rphotos)
                    {
                        if(array_key_exists("name",$rphotos))
                            if($rphotos['name']=='play')
                                $index=$k;
                    }
                }
            }
        }
    }
    //echo $index;
    

    // Now to update this value in your database use this code...

    if($index!=='')
    {
        //Run like this in Shell
        //db.testarray.update({"albums.photos._id":ObjectId("4f545d1bc328103812d00000")},{'$set':{"albums.$.photos.1.name":"play132"}})
        $condition=array("albums.photos._id"=>new MongoId("4f545d1bc328103812d00000"));
        $data=array('$set'=>array("albums.$.photos.".$index.".name"=>"play photo"));
        $result=$db->testarray->update($condition,$data);
        $status=$db->Command(array('getlasterror'=>1));
        print_r($status);
    }
    

提交回复
热议问题