>  기사  >  백엔드 개발  >  mongo 라이브러리를 로컬로 내보내는 방법에 대한 문제 해결

mongo 라이브러리를 로컬로 내보내는 방법에 대한 문제 해결

不言
不言원래의
2018-07-10 15:24:521367검색

이 글에서는 주로 특정 참조 가치가 있는 mongo 라이브러리를 로컬로 내보내는 방법을 소개합니다. 이제 모든 사람과 공유합니다. 필요한 친구가 참조할 수 있습니다.

요구 사항:

yii 프레임워크에서 프로덕션 mongo 라이브러리 데이터를 json으로 내보내기 파일을 로컬

전화로 다운로드하세요.

1. /web/Controllers/TestController.php

 public function actionExport()
    {
        public $target='/WWW/web/html/import/';  //windows 导出文件所在目录
        $export =new Export($target,'QuestionUser',96);
    }

에 견적을 내세요. 2. /web/model

<?php
/*导出mongo库中的数据
* @author lizhihui 
* @date 2018-5-29
* 调用例子:Export(&#39;MyModel&#39;,96);    //导出数据库MyModel中qId为96的数据
*/
Class Export
{
    public $target;
    public $model;    //数据库对象 string,例如:&#39;QuestionAnswer&#39;,&#39;QuestionUser&#39;
    public $qId;    //问卷id int
    public $db;

     /*
     * $target 导出文件所在目录
     * $model
     * $qId  
     */
     public function __construct($target,$model,$qId)
     {
         $this->target = $target;
         $this->db=$model;
         $this->model = new $model;
         $this->qId = (int)$qId;
         $this->export();
     }



    /**
    * 导出mongo生产数据用于本地测试
    * @author lizhihui 
    * @date 2018-5-29
    */
    public function Export()
    {
        $iCount = $this->model->count(array(
            'conditions'=>array(
                'qId'=>array('equals' => $this->qId),
            ))
        );
        if(!$iCount){
            $this->showMessage('数据为空');
        }

        $nStart = 0; //起始记录
        $nCount = 100; //每次处理记录数
        $nPage = intval($iCount/$nCount)+1;
        $aReault=array(); 
        for ($i=0;$i<$nPage;) {
            $sWhere = array(
                &#39;conditions&#39;=>array(
                    'qId'=>array('equals' => $qId),
                ),
                'limit'=>$nCount,
                'offset'=>$nStart,
            );

            $arr = $this->model->findAll($sWhere);
            if(!is_dir($this->target)){
                mkdir($this->target);
            }
            //写入文件
            $limit = 1000;//每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
            foreach ($arr as $key => $val) 
            {
                if($key!=0 && $key%$limit==0){
                    ob_flush();
                    flush();
                }
                $attr=$val->attributes;
                //整理数据,删除不必要的键值
                unset($attr['_id']);
                unset($attr['current_db']);
                unset($attr['pageInfo']);
                $aReault[]=$attr;
            }
            $i++;          
            $nStart = $i*$nCount;
        }
        $filePath=$this->target.$this->db.'_'.$this->qId.'.json';
        file_put_contents($filePath,json_encode($aReault));

        //下载文件
        if(!file_exists($filePath)){
            $this->showMessage('目标文件不存在!');
        }
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename='.$this->db.'_'.$this->qId.'.json');     
        header('Accept-Ranges: bytes');
        echo file_get_contents($filePath);

    }


    /**
     * 信息输出
     */
    private function showMessage($str, $err = 0) {
        if (!$str) {
            return false;
        }
        if ($err) {
            echo "[ERROR]";
        } else {
            echo "[SUCCESS]";
        }

        echo date("Y-m-d H:i:s", time()) . " " . $str . "\n";
        exit;
    }
}

에 Import.php를 만드세요. 이것이 이 글의 내용입니다. 모든 분들의 학습에 도움이 될 것입니다. 더 많은 관련 내용을 보시려면 PHP 중국어 웹사이트를 주목해주세요!

관련 권장 사항:

yii 프레임워크에서 디렉터리의 파일을 데이터베이스로 검색하는 방법

위 내용은 mongo 라이브러리를 로컬로 내보내는 방법에 대한 문제 해결의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.