```
/**
* 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;
}
}
```