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 )