直连王php,php直连mongo

```

/**

* Created by PhpStorm.

* User: root

* Date: 20-11-17

* Time: 下午4:23

*/

class MongoDBInstance {

static $instance;

function __construct () {}

function __clone () {}

public static function getInstance($config){

if (!self::$instance instanceof \MongoDB\Driver\Manager){

if (empty($config['user'])){

self::$instance = new MongoDB\Driver\Manager('mongodb://'.$config['host'].':'.$config['port']);

}else{

self::$instance = new MongoDB\Driver\Manager('mongodb://'.$config['user'].':'.$config['pwd'].'@'.$config['host'].':'.$config['port']);

}

}

return self::$instance;

}

public static function distinct(\MongoDB\Driver\Manager $instance,$dbName,$collName, $key, array $where){

$result = [];

$cmd = [

'distinct' => $collName,

'key' => $key,

'query' => $where

];

$arr = self::command($instance,$dbName,$cmd)->toArray();

if (!empty($arr)) {

$result = $arr[0]->values;

}

return $result;

}

public static function command(\MongoDB\Driver\Manager $instance,$dbName,array $param){

$cmd = new \MongoDB\Driver\Command($param);

return $instance->executeCommand($dbName, $cmd);

}

public static function insertMongo(\MongoDB\Driver\Manager $instance,$dbName,$tableName,$docs = []){

try{

if (empty($docs)) return false;

$bulk = new MongoDB\Driver\BulkWrite;

foreach ($docs as $doc){

$bulk->insert($doc);

}

$res = $instance->executeBulkWrite($dbName . "." . $tableName, $bulk);

$insertCount = $res->getInsertedCount();

if ( $insertCount > 0 ){

return true;

}else{

return false;

}

}catch (Exception $e){

echo $e->getMessage();

}

return false;

}

}

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值