<?php
use MongoDB\Driver\Manager;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\WriteConcern;
use MongoDB\Driver\Query;
use MongoDB\Driver\Command;
class MongoDb {
protected $mongodb;
protected $database;
protected $collection;
protected $bulk;
protected $writeConcern;
protected $defaultConfig
= [
'hostname' => 'localhost',
'port' => '27017',
'username' => '',
'password' => '',
'database' => 'test'
];
public function __construct($config) {
$config = array_merge($this->defaultConfig, $config);
$mongoServer = "mongodb://";
if ($config['username']) {
$mongoServer .= $config['username'] . ':' . $config['password'] . '@';
}
$mongoServer .= $config['hostname'];
if ($config['port']) {
$mongoServer .= ':' . $config['port'];
}
$mongoServer .= '/' . $config['database'];
$this->mongodb = new Manager($mongoServer);
$this->database = $config['database'];
$this->collection = $config['collection'];
$this->bulk = new BulkWrite();
$this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
}
public function query($where = [], $option = []) {
$query = new Query($where, $option);
$result = $this->mongodb->executeQuery("$this->database.$this->collection", $query);
return json_encode($result);
}
public function count($where = []) {
$command = new Command(['count' => $this->collection, 'query' => $where]);
$result = $this->mongodb->executeCommand($this->database, $command);
$res = $result->toArray();
$count = 0;
if ($res) {
$count = $res[0]->n;
}
return $count;
}
public function update($where = [], $update = [], $upsert = false) {
$this->bulk->update($where, ['$set' => $update], ['multi' => true, 'upsert' => $upsert]);
$result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
return $result->getModifiedCount();
}
public function insert($data = []) {
$this->bulk->insert($data);
$result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
return $result->getInsertedCount();
}
public function delete($where = [], $limit = 1) {
$this->bulk->delete($where, ['limit' => $limit]);
$result = $this->mongodb->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);
return $result->getDeletedCount();
}
}