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);
3. MongoDB 屬性修改器
- 用來對文件的某個屬性進行修改
$set 設定
- 不存在屬性則新增, 存在屬性則修改
$data = ["name"=>"小紅","age"=>12,"hobby"=>"dance"];
$collection -> insert($data);
$result = $collection -> find([],[`_id`=>false]);
foreach($result as $key => $value){
echo "<pre>";
var_dump($value);
}
- 修改某個欄位、屬性的值
$new_doc = [
`$set` => ["hobby" => "swim"]
];
$unset 刪除某個屬性
$condition = [`name`=>`小明`];
$new_doc = [
`$unset` => ["hobby" => "swim"]
];
$collection -> update($condition,$new_doc);
$inc 遞增某個屬性
$condition = [`name`=>`小明`];
$new_doc = [
`$inc` => [`age` => 20]
];
$collection -> update($condition,$new_doc);
//原先age=10,現為30
$push 壓入元素到陣列
- 操作的屬性需要是陣列
$data = [`name`=>`小剛`,`age`=>14,`hobby`=>[`read`,`climb`]];
$collection -> insert($data);
- 向hobby屬性(元素),新增元素
$condition = [`name`=>`小剛`];
$new_doc = [
`$push` => [`hobby` => `sing`]
];
$collection -> update($condition,$new_doc);
$pushAll 同時壓入多個元素到陣列
$condition = [`name`=>`小剛`]; $new_doc = [ `$push` => [`hobby` => `sing`,`hobby` => `jump`] ]; $collection -> update($condition,$new_doc);
$addToSet 新增到集合, 不能新增重複元素
$pull 刪除陣列中的某一個元素
$pullAll 刪除多個元素
$pop 彈出元素.