コアクラス群

目次
警告

この拡張モジュールは非推奨です。 かわりに MongoDB 拡張モジュールを使うべきです。

これらのクラスは、ドライバの最も重要な部分です。

MongoClient クラス

警告

このクラスを定義している拡張モジュールは非推奨です。 かわりに MongoDB 拡張モジュールを使うべきです。 このクラスの代替として、以下が使えます。

  • MongoDB\Driver\Manager

はじめに

PHP と MongoDB の接続を管理します。

このクラスを使って、接続を作ったり管理したりします。典型的な使いかたは、このようになります。

例1 MongoClient の基本的な使いかた

<?php

$m 
= new MongoClient(); // 接続します
$db $m->foo// "foo" というデータベースを取得します

?>

接続の作成に関する詳細な情報は、 MongoClient::__construct および 接続 のセクションを参照ください。

クラス概要

MongoClient
class MongoClient {
/* 定数 */
const string MongoClient::VERSION ;
const string MongoClient::DEFAULT_HOST = "localhost" ;
const int MongoClient::DEFAULT_PORT = 27017 ;
const string MongoClient::RP_PRIMARY = "primary" ;
const string MongoClient::RP_PRIMARY_PREFERRED = "primaryPreferred" ;
const string MongoClient::RP_SECONDARY = "secondary" ;
const string MongoClient::RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
const string MongoClient::RP_NEAREST = "nearest" ;
/* プロパティ */
public bool $connected = false ;
public string $status = null ;
protected string $server = null ;
protected bool $persistent = null ;
/* メソッド */
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => true) [, array $driver_options ]]] )
public bool Mongo::close ([ boolstring $connection ] )
public bool Mongo::connect ( void )
public array dropDB ( mixed $db )
public MongoDB Mongo::__get ( string $dbname )
public static array getConnections ( void )
public array Mongo::getHosts ( void )
public array getReadPreference ( void )
public array getWriteConcern ( void )
public bool killCursor ( string $server_hash , intMongoInt64 $id )
public array listDBs ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string Mongo::__toString ( void )
}

定義済み定数

MongoClient 定数

MongoClient::VERSION
PHP ドライバのバージョン。中間バージョンの場合は最後に "dev" や "+"、そして "-" がつくことがあります。
MongoClient::DEFAULT_HOST
ホストを指定しない場合に接続するホスト。
MongoClient::DEFAULT_PORT
ポートを指定しない場合に接続するポート。
MongoClient::RP_PRIMARY
プライマリのレプリカセットメンバーを 優先読み込み する。
MongoClient::RP_PRIMARY_PREFERRED
プライマリのレプリカセットメンバーのほうを優先して 優先読み込み する。
MongoClient::RP_SECONDARY
セカンダリのレプリカセットメンバーを 優先読み込み する。
MongoClient::RP_SECONDARY_PREFERRED
セカンダリのレプリカセットメンバーの方を優先して 優先読み込み する。
MongoClient::RP_NEAREST
最も近いレプリカセットメンバーを 優先読み込み する。

フィールド

connected

このプロパティに true が設定されるのは、データベース接続がオープンしている場合です。 それ以外の場合は false が設定されます。 レプリカセットへの接続の場合は、現在の優先読み込みにマッチするノードに接続している場合にのみ true となります。 このプロパティは、認証を考慮しません。

このプロパティは、バージョン 1.5.0 以降で 非推奨 となりました。

status

このプロパティはもう使われておらず、値は null に設定されます。 バージョン 1.1.x より前のドライバでは、持続的接続を使う場合にここに文字列 ("recycled""new" など) が設定されていました。

このプロパティは、バージョン 1.5.0 以降で 非推奨 となりました。

参考

MongoDB クラス

はじめに

このクラスのインスタンスを使用してデータベースとのやりとりを行います。 データベースを取得するには、このようにします。

例1 データベースの選択

<?php

$m 
= new MongoClient(); // 接続
$db $m->selectDB("example");

?>
データベース名には、ASCII の範囲内でほとんどの文字を使うことができます。 しかし、" " や "." を使うことはできず、空文字列にすることもできません。 "system" という名前も予約済みで、使うことができません。

あまり一般的ではありませんが、 "null"、"[x,y]"、"3"、"\""、"/" などは正しい形式のデータベース名です。

コレクション名とは異なり、データベース名には "$" を含めてもかまいません。

クラス概要

MongoDB
class MongoDB {
/* 定数 */
const int MongoDB::PROFILING_OFF = 0 ;
const int MongoDB::PROFILING_SLOW = 1 ;
const int MongoDB::PROFILING_ON = 2 ;
/* フィールド */
public int $w = 1 ;
public int $wtimeout = 10000 ;
/* メソッド */
public array authenticate ( string $username , string $password )
public array command ( array $command [, array $options = array() [, string &$hash ]] )
public __construct ( MongoClient $conn , string $name )
public MongoCollection createCollection ( string $name [, array $options ] )
public array createDBRef ( string $collection , mixed $document_or_id )
public array drop ( void )
public array dropCollection ( mixed $coll )
public array execute ( mixed $code [, array $args = array() ] )
public bool forceError ( void )
public MongoCollection __get ( string $name )
public array getCollectionInfo ([ array $options = array() ] )
public array getCollectionNames ([ array $options = array() ] )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array lastError ( void )
public array listCollections ([ array $options = array() ] )
public array prevError ( void )
public array repair ([ bool $preserve_cloned_files = false [, bool $backup_original_files = false ]] )
public array resetError ( void )
public MongoCollection selectCollection ( string $name )
public int setProfilingLevel ( int $level )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
public string __toString ( void )
}

定義済み定数

MongoDB ログレベル

MongoDB::PROFILING_OFF
プロファイリングをオフにします。
MongoDB::PROFILING_SLOW
襲い接続 (>100 ms) に対するプロファイリングをオンにします。
MongoDB::PROFILING_ON
すべての操作に対するプロファイリングをオンにします。

フィールド

w
1

成功を返す前に変更をレプリケートするサーバーの数。このクラスの派生クラスである MongoCollection に継承されます。 w の機能が使えるのは、バージョン 1.5.1 以降の MongoDB サーバーと バージョン 1.0.8 以降のドライバを使っている場合のみです。

w は、通知レベルを調整したい場合に使います (MongoCollection::insertMongoCollection::updateMongoCollection::removeMongoCollection::save そして MongoCollection::ensureIndex はすべて、このオプションをサポートしています)。 デフォルト値 (1) の場合、安全な操作は、 データベースサーバーでの操作が一度成功すれば結果を返します。 セカンダリへのレプリケーションが完了する前にサーバーが落ちてしまうと、 その操作が永遠に失われてしまう可能性があります。そこで w の値を 1 より大きく設定し、 少なくとも一台のセカンダリでの操作が完了してからでないと処理が成功したと見なさないようにするのです。

たとえば w を 2 にすると、メインのサーバー以外に ひとつのセカンダリ上で操作が記録されない限り、ドライバは MongoCursorException をスローします。 w の数をプライマリと全セカンダリの総数に設定したくなるかもしれませんが、 もしそうすると、ひとつのセカンダリがダウンしただけで操作が失敗して例外が発生するようになります。 通常は、w=2 (プライマリ、そしてセカンダリ一台) としておくのがいちばん安全でしょう。

wtimeout
10000

MongoDB::$w のレプリケーションが完了するまでに待つミリ秒数。 このクラスの派生クラスである MongoCollection に継承されます。 w の機能が使えるのは、バージョン 1.5.1 以降の MongoDB サーバーと バージョン 1.0.8 以降のドライバを使っている場合のみです。

wtimeout を設定しなければ、w のサーバーへのレプリケーションが完了するまでずっと待ち続けます。 ドライバのデフォルトは 10 秒ですが、この値を変更して挙動を変えることができます。

参考

MongoDB コアドキュメントの » データベース を参照ください。

MongoCollection クラス

はじめに

MongoDB のコレクションを表します。

コレクション名は ASCII セット内の任意の文字を使用できます。たとえば ""、"..."、"my collection" そして "*&#@" といった名前をつけることができます。

ユーザー定義のコレクション名には $ 記号を含めることができません。システムコレクションの中には $ を名前に使うものがあります (local.oplog.$main など) が、 これは予約文字です。名前に $ を含むコレクションを作ったり使ったりしようとすると、 MongoDB が assert を出します。

クラス概要

MongoCollection
class MongoCollection {
/* 定数 */
const int MongoCollection::ASCENDING = 1 ;
const int MongoCollection::DESCENDING = -1 ;
/* フィールド */
public MongoDB $db = null ;
public int $w ;
public int $wtimeout ;
/* メソッド */
public array aggregate ( array $pipeline [, array $options ] )
public MongoCommandCursor aggregateCursor ( array $command [, array $options ] )
public mixed batchInsert ( array $a [, array $options = array() ] )
public __construct ( MongoDB $db , string $name )
public int count ([ array $query = array() [, array $options = array() ]] )
public array createDBRef ( mixed $document_or_id )
public bool createIndex ( array $keys [, array $options = array() ] )
public array deleteIndex ( stringarray $keys )
public array deleteIndexes ( void )
public arrayfalse distinct ( string $key [, array $query ] )
public array drop ( void )
public bool ensureIndex ( stringarray $key|keys [, array $options = array() ] )
public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )
public array findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )
public array findOne ([ array $query = array() [, array $fields = array() [, array $options = array() ]]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array getWriteConcern ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public boolarray insert ( arrayobject $document [, array $options = array() ] )
public array[MongoCommandCursor] parallelCollectionScan ( int $num_cursors )
public boolarray remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( arrayobject $document [, array $options = array() ] )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public bool setWriteConcern ( mixed $w [, int $wtimeout ] )
static protected string toIndexString ( mixed $keys )
public string __toString ( void )
public boolarray update ( array $criteria , array $new_object [, array $options = array() ] )
public array validate ([ bool $scan_data = false ] )
}

定義済み定数

MongoCollection::ASCENDING
ソートやインデックス作成時に使用する「昇順」。
MongoCollection::DESCENDING
ソートやインデックス作成時に使用する「降順」。

フィールド

db

このコレクションの "親" データベース。

w

成功を返す前に変更をレプリケートするサーバーの数。 この値は親データベースから引き継ぎます。 MongoDB クラスのマニュアルに、 w の挙動についてのより詳細な説明があります。

wtimeout

$this->w のレプリケーションが完了するまでに待つミリ秒数。 この値は親データベースから引き継ぎます。 MongoDB クラスのマニュアルに、 wtimeout の挙動についてのより詳細な説明があります。

参考

MongoDB コアドキュメントの » コレクション を参照ください。

MongoCursor クラス

はじめに

カーソルは、データベースクエリの結果を反復処理するときに使います。 たとえば、データベースに問い合わせたすべての結果を見るには次のようにします。

例1 MongoCursor の基本的な使いかた

<?php

$cursor 
$collection->find();
var_dump(iterator_to_array($cursor));

?>

一般に、カーソルを作るときに MongoCursor のコンストラクタを使うことはありません。 新しいカーソルを作るには、(上の例のように) MongoCollection::find をコールします。

上の例で、仮に $collection が 50GB のコレクションだったとしましょう。そんなときに、 結果をすべて一度にメモリに読み込もうとは思わないでしょう。 そんなときのためにカーソルが存在します。 カーソルを使えば、クライアント側から少しずつコレクションにアクセスできるのです。

結果セットが大規模になっても、それを反復処理して 一度にメモリに取り込むデータ量を数メガバイト程度にすることができます。 たとえばこのようにします。

例2 MongoCursor の反復処理

<?php

$cursor 
$collection->find();

foreach (
$cursor as $doc) {
    
// ここで各ドキュメントについて何らかの処理をします
}

?>
これはコレクション内の各ドキュメントを順にたどり、 必要に応じてドキュメントの読み込みやガベージコレクションを行います。

カーソルにデータベースの結果が "含まれている" わけではないことに注意しましょう。 カーソルは単に結果を管理するだけのものです。つまり、 (var_dumpprint_r で) カーソルの内容を出力してもドキュメントは見えません。 単にカーソルオブジェクトが表示されるだけです。 ドキュメント自身を取得するには、上のメソッドのいずれかを使います。

カーソルのステージ

MongoCursor には二段階の「ライフステージ」があります。 クエリ前とクエリ後です。 カーソルを作った時点ではまだデータベースに接続していません。 つまり、クエリ前の段階です。この段階では、クエリに何をしてほしいのかをさらに指定することができます。 取得数の制限や読み飛ばし、ソートなどのオプションを指定できるのです。

クライアントが結果を取得しようとする (直接的あるいは間接的に MongoCursor::next をコールする) と、 そのカーソルはクエリ後の段階に進みます。

例3 MongoCursor へのオプションの追加

<?php

$cursor 
$collection->find()->limit(10);

// まだデータベースへの問い合わせは行われていないので、検索オプションをさらに追加することができます
$cursor $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// ここでデータベースへの問い合わせが行われるので、これ以降はオプションを追加することはできません

// つまり、これは例外をスローします
$cursor->skip(4);
?>

クラス概要

MongoCursor
class MongoCursor implements MongoCursorInterface , Iterator {
/* 静的フィールド */
static bool $slaveOkay = false ;
static int $timeout = 30000 ;
/* メソッド */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor awaitData ([ bool $wait = true ] )
public MongoCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ bool $foundOnly = false ] )
public array current ( void )
public bool dead ( void )
protected void doQuery ( void )
public array explain ( void )
public MongoCursor fields ( array $f )
public array getNext ( void )
public array getReadPreference ( void )
public bool hasNext ( void )
public MongoCursor hint ( mixed $index )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public stringint key ( void )
public MongoCursor limit ( int $num )
public MongoCursor maxTimeMS ( int $ms )
public array next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor setFlag ( int $flag [, bool $set = true ] )
public MongoCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ bool $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ bool $tail = true ] )
public MongoCursor timeout ( int $ms )
public bool valid ( void )
}

静的変数

slaveOkay

クエリに "slaveOkay" フラグが設定されていると、セカンダリ側での読み込みを許可します (セカンダリは、デフォルトでは単なるバックアップ用であり読み込みはできません)。 MongoCursor::slaveOkay で上書きすることができます。

この機能は 非推奨 です。かわりに 優先読み込み を使いましょう。

timeout

データベースからのすべての応答に対するタイムアウトをミリ秒単位で設定します。 ずっと待ち続ける場合は -1 を指定します。 MongoCursor::timeout で上書きすることができます。 これは MongoDB サーバーに対する操作をキャンセルするわけではなく、 単にドライバ側で応答を待つのをやめて MongoCursorTimeoutException をスローするだけです。

参考

MongoDB コアドキュメントの » カーソル を参照ください。

The MongoCursorInterface interface

はじめに

Interface for cursors, which can be used to iterate through results of a database query or command. This interface is implemented by the MongoCursor and MongoCommandCursor classes.

注意: Similar to Traversable, this interface cannot be implemented in PHP scripts.

クラス概要

MongoCursorInterface
class MongoCursorInterface extends Iterator {
/* メソッド */
abstract public MongoCursorInterface batchSize ( int $batchSize )
abstract public bool dead ( void )
abstract public array getReadPreference ( void )
abstract public array info ( void )
abstract public MongoCursorInterface setReadPreference ( string $read_preference [, array $tags ] )
abstract public MongoCursorInterface timeout ( int $ms )
/* 継承したメソッド */
abstract public mixed Iterator::current ( void )
abstract public scalar Iterator::key ( void )
abstract public void Iterator::next ( void )
abstract public void Iterator::rewind ( void )
abstract public bool Iterator::valid ( void )
}

The MongoCommandCursor class

はじめに

A command cursor is similar to a MongoCursor except that you use it for iterating through the results of a database command instead of a normal query. Command cursors are useful for iterating over large result sets that might exceed the document size limit (currently 16MB) of a single MongoDB::command response.

While you can create command cursors using MongoCommandCursor::__construct or the MongoCommandCursor::createFromDocument factory method, you will generally want to use command-specific helpers such as MongoCollection::aggregateCursor.

Note that the cursor does not "contain" the database command's results; it just manages iteration through them. Thus, if you print a cursor (f.e. with var_dump or print_r), you will see the cursor object but not the result documents.

Cursor Stages

A MongoCommandCursor has two "life stages": pre- and post- command. When a cursor is created, it has not yet contacted the database, so it is in its pre-command state. When the client first attempts to get a result (by calling MongoCommandCursor::rewind, directly or indirectly), the cursor moves into the post-command state.

The command cursor's batch size and socket timeout may be configured in both the pre- and post- command states.

例1 Adding options to MongoCommandCursor

<?php

$cursor 
= new MongoCommandCursor(...);

$cursor $cursor->batchSize);

foreach (
$cursor as $result) {
    
var_dump($result);
}
?>

クラス概要

MongoCommandCursor
class MongoCommandCursor implements MongoCursorInterface , Iterator {
/* メソッド */
public MongoCommandCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns , array $command = array() )
public static MongoCommandCursor createFromDocument ( MongoClient $connection , string $hash , array $document )
public array current ( void )
public bool dead ( void )
public array getReadPreference ( void )
public array info ( void )
public int key ( void )
public void next ( void )
public array rewind ( void )
public MongoCommandCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCommandCursor timeout ( int $ms )
public bool valid ( void )
}

参考

  • MongoDB::command
  • MongoCollection::aggregateCursor