1. 程式人生 > >MongoDB相關操作

MongoDB相關操作

操作 ins 若有 god 更新 屬性修改 創建 pre upd

1. 連接MongoDB

<?php
    //1.連接到MongoDB
    $host = "127.0.0.1";
    $port = 27017;
    $server = "mongodb://$host:$port";
    $mongodb = new MongoClient($server);
    echo "<pre>";
    var_dump($mongodb);
    //2.選擇數據庫
    $db = $client -> hytc;
    var_dump($db);
    //3.選擇數據表
    $collection = $db
-> user; var_dump($collection);

註:庫、表無需手動創建,選擇後自動創建

2. CRUD操作

insert(數據)  插入數據(必是一個數組)

  //插入文檔(關聯數組)
  $data = ["name"=>"小明","age"=>10,"hobby"=>"swim"];
  $result = $collection -> insert($data);
  echo "<pre>";
  var_dump($result);

find(查找條件,查找字段)  查詢數據

    //查詢數據(返回的是cursor遊標,資源)
$condition = [‘name‘=>‘小明‘]; $fields = [ ‘_id‘ => false, //不查詢id ‘name‘ => true, //查詢name ‘hobby‘ => true //查詢hobby ]; $result = $collection -> find($condition,$fields); foreach($result as $key => $value){ echo "<pre>";
var_dump($value); }

update(查找條件,更新之後的內容=>文檔內容)  更新數據

    //更新數據
    $condition = [‘name‘=>‘小明‘];
    $new_doc = [
        ‘$set‘ => ["hobby" => "swim"]
    ];
    $result = $collection -> update($condition,$new_doc);
    echo "<pre>";
    var_dump($result);

註:

  • 若不存在hobby字段,則創建該字段
  • 默認更新會進行替換操作,可通過屬性修改器進行修改而不是替換
  • 若有多條記錄符合更新條件,默認只會更新第一個數據
  • 若需更新符合更新條件的所有記錄,則設置該函數的第三個參數:[“multiple”=>true]
        //更新數據
        $condition = [‘age‘=>‘20‘];
        $new_doc = [
            ‘$set‘ => ["hobby" => "swim"]
        ];
        $result = $collection -> update($condition,$new_doc,[‘multiple‘=>true]);
        echo "<pre>";
        var_dump($result);

remove(查找條件)  刪除數據

    //刪除數據
    $condition = [‘name‘=>‘小明‘];
    $result = $collection -> remove($condition);

MongoDB相關操作