본문 바로가기

php

mongodb php 작성법

다음 코드를 사용하려면 mongodb와 연동되는 php 드라이버를 설치해야한다 필자 경우에서는 pecl을 이용해서 mongodb php driver를 설치했다.


<?php
    /*에러 검출 코드*/
    error_reporting(E_ALL);

    ini_set("display_errors", 1);

    /*드라이버*/
    $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");

    $bulk = new MongoDB\Driver\BulkWrite;

    $query = new MongoDB\Driver\Query([]);


    /* namespace 는 db_name.collection_name
     * $mng->executeBulkWrite('namespace', $bulk); */
    $rows = $mng->executeQuery("whot.analysis", $query);


    $return_array = array();

    /*select 배열을 가져와서 json으로 변경*/
    foreach ($rows as $row) {
    array_push($return_array,
     array(
     "_id" => "$row->_id",
     "age" => $row->age
    ));
    }
    $json= json_encode($return_array);
    echo $json;

    /*update문 new_data는 배열로 삽입*/
    //$doc = ['_id' => 'a'];
    //$new_data =['$set' =>['age' => 'd']];
    //$bulk -> update($doc,$new_data);

    /*update push문 new_data가 배열일때만 가능하다*/
    //$doc = ['_id' => 'b'];
    //$new_data =['$push' => ['age' => 'e']];
    //$bulk -> update($doc,$new_data);



    //insert문
    //$doc = ['_id' => 'a', 'age' => 'b'];
    //$bulk->insert($doc);
    
    //update문 배열
    //$doc = ['_id' => 'a'];
    //$new_data =['$set' =>['age' => ['d']]];
    //$bulk -> update($doc,$new_data);
?>


'php' 카테고리의 다른 글

PhP Storm 연동하기  (2) 2018.07.03
Address already in use (Bind failed) 에러 해결하기  (0) 2018.04.03
FCM 주제단위로 전송하기  (0) 2018.04.01