zoukankan      html  css  js  c++  java
  • PHP7 MongDB 安装与使用

    我们使用 pecl 命令来安装:

     /usr/local/php7/bin/pecl install mongodb

    执行成功后,会输出以下结果:

    ……
    Build process completed successfully
    Installing '/usr/local/php7/lib/php/extensions/no-debug-non-zts-20151012/mongodb.so'
    install ok: channel://pecl.php.net/mongodb-1.1.7
    configuration option "php_ini" is not set to php.ini location
    You should add "extension=mongodb.so" to php.ini

    接下来我们打开 php.ini 文件,添加 extension=mongodb.so 配置。

    可以直接执行以下命令来添加。

    echo "extension=mongodb.so" >> `/usr/local/php7/bin/php --ini | grep "Loaded Configuration" | sed -e "s|.*:s*||"`

    注意:以上执行的命令中 php7 的安装目录为 /usr/local/php7/,如果你安装在其他目录,需要相应修改 pecl 与 php 命令的路径。

    Mongodb 使用

    PHP7 连接 MongoDB 语法如下:

    $manager = new MongoDBDriverManager("mongodb://localhost:27017");

    插入数据

    将 name 为"baidu" 的数据插入到 test 数据库的 runoob 集合中。

    <?php
    $bulk = new MongoDBDriverBulkWrite;
    $document = ['_id' => new MongoDBBSONObjectID, 'name' => 'baidu'];
    
    $_id= $bulk->insert($document);
    
    var_dump($_id);
    
    $manager = new MongoDBDriverManager("mongodb://localhost:27017");  
    $writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000);
    $result = $manager->executeBulkWrite('test.runoob', $bulk, $writeConcern);
    ?>

    读取数据

    这里我们将三个网址数据插入到 test 数据库的 sites 集合,并读取迭代出来:

    <?php
    $manager = new MongoDBDriverManager("mongodb://localhost:27017");  
    
    // 插入数据
    $bulk = new MongoDBDriverBulkWrite;
    $bulk->insert(['x' => 1, 'name'=>'Baidu', 'url' => 'http://www.baidu.com']);
    $bulk->insert(['x' => 2, 'name'=>'Google', 'url' => 'http://www.google.com']);
    $bulk->insert(['x' => 3, 'name'=>'taobao', 'url' => 'http://www.taobao.com']);
    $manager->executeBulkWrite('test.sites', $bulk);
    
    $filter = ['x' => ['$gt' => 1]];
    $options = [
        'projection' => ['_id' => 0],
        'sort' => ['x' => -1],
    ];
    
    // 查询数据
    $query = new MongoDBDriverQuery($filter, $options);
    $cursor = $manager->executeQuery('test.sites', $query);
    
    foreach ($cursor as $document) {
        print_r($document);
    }
    ?>

    输出结果为:

    stdClass Object
    (
        [x] => 3
        [name] => taobao
        [url] => http://www.taobao.com
    )
    stdClass Object
    (
        [x] => 2
        [name] => Google
        [url] => http://www.google.com
    )
  • 相关阅读:
    如何取消IntelliJ IDEA打开默认项目配置
    SQL注入和XSS攻击的原理
    什么是SQL注入?什么是XSS攻击?什么是CSRF攻击?
    jQuery动态添加删除CSS样式
    ArcGisJS实现地图常用工具条、距离测量和面积测量(非官方实例)
    Visual Studio Code打开终端控制台
    IntelliJ IDEA热部署教程,只要两步!
    Visual Studio Code 设置中文语言版本
    Visual Studio Code 入门教程
    使用bind配置DNS服务(CentOS 6.5)
  • 原文地址:https://www.cnblogs.com/mmady/p/8778447.html
Copyright © 2011-2022 走看看