1. 程式人生 > >tp5+Mongodb的特殊操作

tp5+Mongodb的特殊操作

Push操作

新增資料

public function add(){
        $this->data = [
            '作者'    =>  'tuzi',
            '年齡'    =>  '22',
            '標題'    =>  '防塔與補兵',
            '評論'    =>  [
                [
                    '序號'    => '001',
                    '內容'    => '五殺'
                ]
            ]
        ];
        $res
= Db::table('document')->insert($this->data); if($res){ echo "success"; }else{ echo "error"; } }

結果

array(1) {
  [0] => array(5) {
    ["_id"] => object(MongoDB\BSON\ObjectId)#12 (1) {
      ["oid"] => string(24) "5a51f73083869e4b65549c36"
} ["作者"] => string(4) "tuzi" ["年齡"] => string(2) "22" ["標題"] => string(15) "防塔與補兵" ["評論"] => array(1) { [0] => array(2) { ["序號"] => string(3) "001" ["內容"] => string(6) "五殺" } } } }

利用push更新資料

public function update()
    {
$update_data['評論'] = [ '$push', [ '序號' => '002', '內容' => '三殺' ] ]; $update_res = Db::table('document')->where('標題','防塔與補兵')->update($update_data); if($update_res){ echo "success"; }else{ echo "error"; } }

結果

array(1) {
  [0] => array(5) {
    ["_id"] => object(MongoDB\BSON\ObjectId)#12 (1) {
      ["oid"] => string(24) "5a51f73083869e4b65549c36"
    }
    ["作者"] => string(4) "tuzi"
    ["年齡"] => string(2) "22"
    ["標題"] => string(15) "防塔與補兵"
    ["評論"] => array(2) {
      [0] => array(2) {
        ["序號"] => string(3) "001"
        ["內容"] => string(6) "五殺"
      }
      [1] => array(2) {
        ["序號"] => string(3) "002"
        ["內容"] => string(6) "三殺"
      }
    }
  }
}