Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

分享一个很有用的php7+mongodb类!

作者:只言片語中   发布日期:2023-12-02   浏览:759

以下是一个基于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怎么安装event扩展

下一篇:php7怎么安装stomp扩展

大家都在看

php session用法

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

php ||

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站