以下是一个基于PHP7和MongoDB的简单类示例:
class MongoDBConnection {
private $connection;
private $db;
private $collection;
public function __construct($host, $port, $database, $collection) {
$this->connection = new MongoDB\Driver\Manager("mongodb://$host:$port");
$this->db = $database;
$this->collection = $collection;
}
public function insert($data) {
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert($data);
$this->connection->executeBulkWrite("$this->db.$this->collection", $bulk);
}
public function find($filter) {
$query = new MongoDB\Driver\Query($filter);
$cursor = $this->connection->executeQuery("$this->db.$this->collection", $query);
$result = [];
foreach ($cursor as $document) {
$result[] = $document;
}
return $result;
}
public function update($filter, $update) {
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update($filter, $update);
$this->connection->executeBulkWrite("$this->db.$this->collection", $bulk);
}
public function delete($filter) {
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete($filter);
$this->connection->executeBulkWrite("$this->db.$this->collection", $bulk);
}
}
使用示例:
// 创建MongoDB连接
$mongo = new MongoDBConnection('localhost', 27017, 'mydb', 'mycollection');
// 插入数据
$mongo->insert(['name' => 'John', 'age' => 25]);
// 查询数据
$result = $mongo->find(['age' => 25]);
print_r($result);
// 更新数据
$mongo->update(['name' => 'John'], ['$set' => ['age' => 30]]);
// 删除数据
$mongo->delete(['name' => 'John']);
这个类提供了基本的插入、查询、更新和删除操作,可以根据需要进行扩展和定制。请确保在使用之前安装了MongoDB扩展。
下一篇:php7怎么安装stomp扩展
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站