zoukankan      html  css  js  c++  java
  • 推荐一个php7+ mongodb三方类

     

    5

    由于项目需要,把项目升级到了php7。但是升级了之后发现mongo扩展不能用了。php7.0以上只支持mongodb扩展了。而mongodb扩展的驱动使用起来比monmgo扩展显得很复杂,啰嗦。在网上找了很久。终于找到了一个比较简洁的mongodb类。语法跟mongo的差不多。清晰,自然。

    项目地址https://github.com/mongodb/mongo-php-library

    因为项目是国外友人贡献的。所以没有可以看的很明白的文档。这里整理了一些常用的方法。

    获取实例
    $uri = "mongodb://username:password@host/database";
    $client = new MongoDBClient($uri);
    获取集合
    $collection = $client->selectCollection('test','test');
    获取一条数据
    $data = $collection->findOne(['id'=>1]);
    获取多条数据
    $where = ['type'=>1];
    $options = array(
        'projection' => array('id' => 1, 'age' => 1, 'name' => -1), // 指定返回哪些字段 1 表示返回 -1 表示不返回
        'sort' => array('id' => -1), // 指定排序字段
        'limit' => 10, // 指定返回的条数
        'skip' => 0, // 指定起始位置
    );
    $data = $collection->find($where,$options)->toArray();
    var_dump($data);
    去重
    $fileName = 'name';
    $where = ['id' => ['$lt' => 100]]
    $ret = $this->collection->distinct($fileName,$where);
    插入一条数据
    $data = array(
        'id' => 2,
        'age' => 20,
        'name' => '张三'
    );
    $ret = $collection->insertOne($data);
    $id=$ret->getInsertedId();
    批量插入
    $data = array(
        ['id' => 1, 'age' => 21, 'name' => '1xiaoli'],
        ['id' => 2, 'age' => 22, 'name' => '2xiaoli'],
        ['id' => 3, 'age' => 23, 'name' => '3xiaoli'],
        ['id' => 4, 'age' => 26, 'name' => '4xiaoli'],
        ['id' => 5, 'age' => 24, 'name' => '5xiaoli'],
        ['id' => 6, 'age' => 25, 'name' => '6xiaoli'],
    );
    $ret = $collection->insertMany($data);
    # 返回插入id
    var_dump($ret->getInsertedIds());
    更新一条
    $ret = $collection->updateOne(array('id' => 2), array('$set' => array('age' => 56)));
    更新多条
    $ret = $collection->updateMany(array('id' => ['$gt' => 1]), array('$set' => array('age' => 56, 'name' => 'x')));
    删除一条
    $ret = $collection->deleteOne(array('id' => 2));
    删除多条
    $collection->deleteMany(array('id' => array('$in' => array(1, 2))));
    聚合
     
    $ops = [
        [
            '$match' =>['type'=>['$in'=>[2,4]]]
        ],
        [
            '$sort' => ['list.create_time' => -1]  //sort顺序不能变,否则会造成排序混乱,注意先排序再分页
        ],
        [
            '$skip' => 0
        ],
        [
            '$limit' => 20000
        ],
    ];
    $data = $collection->aggregate($ops);
    foreach ($data as $document)
    {
        var_dump($document);
    }
  • 相关阅读:
    STL--sort源码分析
    进程和线程的区别
    static 关键字 静态成员变量及静态成员函数
    二叉树遍历总结 先序、中序、后续、广度、深度
    C++用new和不用new创建类对象区别
    传输层--TCP和UDP的区别
    传输层的作用
    微信商户/H5支付申请 被拒原因:网站存在不实内容或不安全信息
    Oracle本地网络服务名配置
    存储过程常用技巧
  • 原文地址:https://www.cnblogs.com/brady-wang/p/10490129.html
Copyright © 2011-2022 走看看