MongoDB相关操作
程序员文章站
2022-09-16 18:30:21
PHP连接MongoDB并进行CRUD操作,以及MongoDB属性修改器 ......
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 弹出元素.