博客列表 >PHP用MongoDb实现增删改查

PHP用MongoDb实现增删改查

瞬间
瞬间原创
2020年04月17日 12:59:26563浏览

use app\utils\Mongo;

use MongoDB\BSON\ObjectId;

class BaseModel

{

/*

     * 添加数据公用函数

     * @param $data 新增的数据

     * @param $database 数据库.集合

     * @return Boolean

     * */

public function addCommon($data,$database){

$client = Mongo::get_instance()->get_client();

$bulk = new \MongoDB\Driver\BulkWrite(['order' => true]);

$bulk->insert($data);

$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);

$res = $client->executeBulkWrite($database, $bulk, $writeConcern);

if($res->getInsertedCount()>=1){

return true;

}else{

return false;

}

}

/*

* 编辑公用函数

* @param $id 主键id

* @param $data 要编辑的数据

* @param $database 数据库.集合

* @return Boolean

* */

public function updateCommon($id,$data,$database){

$mongo=Mongo::get_instance()->get_client() ;

$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);

$bulk = new \MongoDB\Driver\BulkWrite;

$bulk->update(

['_id' => new ObjectID($id)],

['$set' => $data],

['multi' => true, 'upsert' => false]

//multi为true,则满足条件的全部修改,默认为true,如果改为false,则只修改满足条件的第一条

//upsert为 true:表示不存在就新增

);

$result = $mongo->executeBulkWrite($database, $bulk, $writeConcern);

if($result->getModifiedCount() >=1){

return true;

}else{

return false;

}

}

/*

* 数据库查询公用函数

* @param $f筛选条件

* @param $op查询内容

* @param $database 数据库.集合

* @return json

* */

public function getCommon($f,$op,$database){

$mongo = Mongo::get_instance()->get_client();

$filter = $f;

$options = $op;

$query = new \MongoDB\Driver\Query($filter,$options);

$rs = $mongo->executeQuery($database,$query);

$arr = $rs->toArray();

return json_encode($arr);

}

/*

* 删除数据公用函数(物理删除)

* @param $where 条件

* @param $database 数据库.集合

* @return Boolean

* */

public function delete($where,$database){

$mongo = Mongo::get_instance();

$bulk = new \MongoDB\Driver\BulkWrite;

$bulk->delete($where); //填写删除的条件

$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);

//执行上面的删除语句

$result = $mongo->get_client()->executeBulkWrite($database, $bulk, $writeConcern);

return $result->getDeletedCount();

}

/*

* 编辑公用函数--多条件

* @param $where

* @param $data

* @param $database

* */

public function updateWhere($where, $data, $database){

$mongo = Mongo::get_instance()->get_client();

$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);

$bulk = new \MongoDB\Driver\BulkWrite;

$bulk->update(

$where,

['$set' => $data],

['multi' => true, 'upsert' => false]

);

$result = $mongo->executeBulkWrite($database, $bulk, $writeConcern);

if($result->getModifiedCount() >=1){

return true;

}else{

return false;

}

}

}


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议