php mongodb driver : mongodb 笔记

mongodb 部分基本类

about mongo和mongodb

mongo驱动已经废弃,不再支持最新版本的mongodb和php

mongodb甚至可以支持HHVM,不过只实现了最小功能,一般需要封装后使用

MongoDB\Driver\Manager 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 MongoDB\Driver\Manager {
/* 方法 */
final public __construct ( string $uri [, array $options [, array $driverOptions ]] )
final public MongoDB\Driver\WriteResult executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )
final public MongoDB\Driver\Cursor executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )
final public MongoDB\Driver\Cursor executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )
final public array getServers ( void )
final public MongoDB\Driver\Server selectServer ( MongoDB\Driver\ReadPreference $readPreference )
}

链接建立

var_dump()是调试的好方法

<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
?>

MongoDB\Driver\Command mongodb命令(主要针对数据库)

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

  $cursor = $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));

MongoDB\Driver\Query class mongodb查询语句(针对集合)

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

MongoDB\Driver\BulkWrite 构建写命令

经过MongoDB\Driver\Manager::executeBulkWrite()传入server

写操作可以是ordered(default)或是unorder

  • ordered :按顺序传入命令,一个操作失败后续所有操作自动取消
  • unordered :任意顺序传入,可以是并行的,任何错误要在所有操作尝试之后再报告
<?php
$bulk = new MongoDB\Driver\BulkWrite(['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 MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

try {
    $result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
    $result = $e->getWriteResult();

    // Check if the write concern could not be fulfilled
    if ($writeConcernError = $result->getWriteConcernError()) {
        printf("%s (%d): %s\n",
            $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)\n",
            $writeError->getIndex(),
            $writeError->getMessage(),
            $writeError->getCode()
        );
    }
} catch (MongoDB\Driver\Exception\Exception $e) {
    printf("Other error: %s\n", $e->getMessage());
    exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated  %d document(s)\n", $result->getModifiedCount());
?>

MongoDB\Driver\WriteConcern 写操作保证级别

类摘要

final MongoDB\Driver\WriteConcern {
/* 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 )
}

MongoDB\Driver\Cursor 存放返回结果

MongoDB\Driver\Cursor::toArray(void)— Returns an array containing all results for this cursor

MongoDB\Driver\Cursor::getId(void) — Returns the ID for this cursor

MongoDB\Driver\Cursor::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();
}

MongoDB\Driver\WriteConcernError

MongoDB\Driver\WriteError

两个的类摘要相同

final MongoDB\Driver\WriteConcernError {
/* 方法 */
final public ReturnType getCode ( void )
final public ReturnType getInfo ( void )
final public ReturnType getMessage ( void )
}

MongoDB\Driver\WriteResult 写操作结果

类摘要

final MongoDB\Driver\WriteResult {
/* 方法 */
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 )
}

MongoDB\Driver\Manager 中方法

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 MongoDB\Driver\WriteResult MongoDB\Driver\Manager::executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, MongoDB\Driver\WriteConcern $writeConcern ] )

参数

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

executeCommand

运行命令

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeCommand ( string $db , MongoDB\Driver\Command $command [, MongoDB\Driver\ReadPreference $readPreference ] )

executeQuery

运行读语句

final public MongoDB\Driver\Cursor MongoDB\Driver\Manager::executeQuery ( string $namespace , MongoDB\Driver\Query $query [, MongoDB\Driver\ReadPreference $readPreference ] )

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

getServers( void )

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

$manager = new MongoDB\Driver\Manager("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 MongoDB\Driver\Command(['ping' => 1]);
$manager->executeCommand('db', $command);

var_dump($manager->getServers());

selectServer

选择一个满足MongoDB\Driver\ReadPreference 变量指定的server

final public MongoDB\Driver\Server MongoDB\Driver\Manager::selectServer ( MongoDB\Driver\ReadPreference $readPreference )