zoukankan      html  css  js  c++  java
  • php mongodb driver : mongodb 笔记

    mongodb 部分基本类

    about mongo和mongodb

    mongo驱动已经废弃,不再支持最新版本的mongodb和php
    mongodb甚至可以支持HHVM,不过只实现了最小功能,一般需要封装后使用

    MongoDBDriverManager class 连接管理

    Any write or query can throw connection exceptions as connections are created lazily. A MongoDB server may also become unavailable during the life time of the script. It is therefore important that all actions on the Manager to be wrapped in try/catch statements.

    manager类所有操作都应该使用try/catch!

    类摘要

    final MongoDBDriverManager {
    /* 方法 */
    final public __construct ( string $uri [, array $options [, array $driverOptions ]] )
    final public MongoDBDriverWriteResult executeBulkWrite ( string $namespace , MongoDBDriverBulkWrite $bulk [, MongoDBDriverWriteConcern $writeConcern ] )
    final public MongoDBDriverCursor executeCommand ( string $db , MongoDBDriverCommand $command [, MongoDBDriverReadPreference $readPreference ] )
    final public MongoDBDriverCursor executeQuery ( string $namespace , MongoDBDriverQuery $query [, MongoDBDriverReadPreference $readPreference ] )
    final public array getServers ( void )
    final public MongoDBDriverServer selectServer ( MongoDBDriverReadPreference $readPreference )
    }
    

    链接建立

    var_dump()是调试的好方法

    <?php
    $manager = new MongoDBDriverManager("mongodb://localhost:27017");
    ?>
    

    MongoDBDriverCommand mongodb命令(主要针对数据库)

    不是用字符串形式表述mongodb命令,而是通过这个类

      $cursor = $manager->executeCommand("databaseName", new MongoDBDriverCommand($collstats));
    

    MongoDBDriverQuery class mongodb查询语句(针对集合)

    $filter = ['id' => 2];
    $options = [
       'projection' => ['_id' => 0],
    ];
    $query = new MongoDBDriverQuery($filter, $options);
    $rows = $mongo->executeQuery('db_name.my_collection', $query); // $mongo contains the connection object to MongoDB
    

    MongoDBDriverBulkWrite 构建写命令

    经过MongoDBDriverManager::executeBulkWrite()传入server
    写操作可以是ordered(default)或是unorder

    • ordered :按顺序传入命令,一个操作失败后续所有操作自动取消
    • unordered :任意顺序传入,可以是并行的,任何错误要在所有操作尝试之后再报告
    <?php
    $bulk = new MongoDBDriverBulkWrite(['ordered' => true]);
    $bulk->delete([]);
    $bulk->insert(['_id' => 1]);
    $bulk->insert(['_id' => 3, 'hello' => 'world']);
    $bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
    $bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
    
    $manager = new MongoDBDriverManager('mongodb://localhost:27017');
    $writeConcern = new MongoDBDriverWriteConcern(MongoDBDriverWriteConcern::MAJORITY, 1000);
    
    try {
        $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
    } catch (MongoDBDriverExceptionBulkWriteException $e) {
        $result = $e->getWriteResult();
    
        // Check if the write concern could not be fulfilled
        if ($writeConcernError = $result->getWriteConcernError()) {
            printf("%s (%d): %s
    ",
                $writeConcernError->getMessage(),
                $writeConcernError->getCode(),
                var_export($writeConcernError->getInfo(), true)
            );
        }
    
        // Check if any write operations did not complete at all
        foreach ($result->getWriteErrors() as $writeError) {
            printf("Operation#%d: %s (%d)
    ",
                $writeError->getIndex(),
                $writeError->getMessage(),
                $writeError->getCode()
            );
        }
    } catch (MongoDBDriverExceptionException $e) {
        printf("Other error: %s
    ", $e->getMessage());
        exit;
    }
    
    printf("Inserted %d document(s)
    ", $result->getInsertedCount());
    printf("Updated  %d document(s)
    ", $result->getModifiedCount());
    ?>
    

    MongoDBDriverWriteConcern 写操作保证级别

    类摘要

    final MongoDBDriverWriteConcern {
    /* Constants */
    const string MAJORITY = majority ;
    /* 方法 */
    final public __construct ( string $w [, integer $wtimeout [, boolean $journal ]] )
    final public bool|null getJournal ( void )
    final public string|int|null getW ( void )
    final public int getWtimeout ( void )
    }
    

    MongoDBDriverCursor 存放返回结果

    MongoDBDriverCursor::toArray(void)— Returns an array containing all results for this cursor
    MongoDBDriverCursor::getId(void) — Returns the ID for this cursor
    MongoDBDriverCursor::getServer(void) — Returns the server associated with this cursor

    以前cursor的sort方法可以通过传query附加选项实现
    cursor没有以前mongo驱动的hasnext()或next()方法
    如果需要改变迭代cursor的行为,可以使用 IteratorIterator 类,注意需要rewind the iterator

    $cursor = $collection->find();
    $it = new IteratorIterator($cursor);
    $it->rewind(); // Very important
    
    while($doc = $it->current()) {
        var_dump($doc);
        $it->next();
    }
    

    MongoDBDriverWriteConcernError

    MongoDBDriverWriteError

    两个的类摘要相同

    final MongoDBDriverWriteConcernError {
    /* 方法 */
    final public ReturnType getCode ( void )
    final public ReturnType getInfo ( void )
    final public ReturnType getMessage ( void )
    }
    

    MongoDBDriverWriteResult 写操作结果

    类摘要

    final MongoDBDriverWriteResult {
    /* 方法 */
    final public ReturnType getDeletedCount ( void )
    final public ReturnType getInsertedCount ( void )
    final public ReturnType getMatchedCount ( void )
    final public ReturnType getModifiedCount ( void )
    final public ReturnType getServer ( void )
    final public ReturnType getUpsertedCount ( void )
    final public ReturnType getUpsertedIds ( void )
    final public ReturnType getWriteConcernError ( void )
    final public ReturnType getWriteErrors ( void )
    }
    

    MongoDBDriverManager 中方法

    executeBulkWrite

    Executes one or more write operations on the primary server.
    A primary server is a server that acts as the first source for Domain Name System (DNS) data and responds to queries. It can be contrasted to the secondary server, which acts like the primary server but does not have the same access to data.

    在主服务器上运行写语句

    final public MongoDBDriverWriteResult MongoDBDriverManager::executeBulkWrite ( string $namespace , MongoDBDriverBulkWrite $bulk [, MongoDBDriverWriteConcern $writeConcern ] )
    

    参数

    • namespace (string) 完整数据库名字空间。例如"databaseName.collectionName"
    • bulk (MongoDBDriverBulkWrite) 需要执行的构建好的命令
    • writeConcern (MongoDBDriverWriteConcern) 写操作确认级别,如果没有给,则使用简历链接时URI中指定的

    executeCommand

    运行命令

    final public MongoDBDriverCursor MongoDBDriverManager::executeCommand ( string $db , MongoDBDriverCommand $command [, MongoDBDriverReadPreference $readPreference ] )
    

    executeQuery

    运行读语句

    final public MongoDBDriverCursor MongoDBDriverManager::executeQuery ( string $namespace , MongoDBDriverQuery $query [, MongoDBDriverReadPreference $readPreference ] )
    

    MongoDBDriverReadPreference 指定了运行这个语句的server,没有时就用简历链接时URI中的

    getServers( void )

    返回manager连接的主机信息,注意建立连接后直接使用有可能为空

    $manager = new MongoDBDriverManager("mongodb://localhost:27017");
    
    /* The driver connects to the database server lazily, so Manager::getServers()
     * may initially return an empty array. */
    var_dump($manager->getServers());
    
    $command = new MongoDBDriverCommand(['ping' => 1]);
    $manager->executeCommand('db', $command);
    
    var_dump($manager->getServers());
    

    selectServer

    选择一个满足MongoDBDriverReadPreference 变量指定的server

    final public MongoDBDriverServer MongoDBDriverManager::selectServer ( MongoDBDriverReadPreference $readPreference )
    
  • 相关阅读:
    C#细说多线程(下)
    C#细说多线程(上)
    C#:进程、线程、应用程序域(AppDomain)与上下文分析
    C#委托与事件
    SQL Server 查询优化器运行方式
    SQL优化之索引分析
    C#反射机制
    Sql注入
    JAVA内存泄漏解决办法
    spring4声明式事务—02 xml配置方式
  • 原文地址:https://www.cnblogs.com/jcuan/p/5634368.html
Copyright © 2011-2022 走看看