downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Mongo::dropDB> <Mongo::connectUtil
[edit] Last updated: Fri, 25 May 2012

view this page in

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct新しいデータベース接続オブジェクトを作成する

説明

public Mongo::__construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )

パラメータを省略した場合は、"localhost:27017" (あるいは php.ini の mongo.default_hostmongo.default_port で設定した場所) に接続します。

server は次のような形式にしなければなりません。

mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db

接続文字列は常に mongodb:// で始まります。 この部分が、接続文字列であることを表しています。

usernamepassword を指定すれば、コンストラクタが接続を確立する際にデータベースへの認証を試みます。 ユーザー名とパスワードはオプションで、もし指定するならその後に @ を続けなければなりません。

少なくともひとつのホストを指定しなければなりません (ポートはオプションで、デフォルトは常に 27017 となります)。 そのあとに、接続させたいホストをいくつでも続けることができます。 ホスト名はカンマ区切りで並べ、少なくともひとつのホストへの接続が成功すれば コンストラクタは正常な結果を返します。 どのホストにも接続できなかった場合は MongoConnectionException をスローします。

ユーザー名とパスワードを指定したときには、認証先のデータベースも指定することになるでしょう。 db を省略した場合は "admin" を使います。

パラメータ

server

サーバー名。

options

接続オプションの配列。現在使用できるオプションは次のとおりです。

  • "connect"

    コンストラクタで接続を行うか。デフォルトは TRUE

  • "timeout"

    ドライバがデータベースへの接続を試みる時間の長さ (ミリ秒単位)。

  • "replicaSet"

    接続先のレプリカセットの名前。指定した場合は、シードのデータベースコマンド ismaster を使ってマスタを決定します。 ドライバは、リストに上がっていないサーバーに接続することになるかもしれません。 詳細は、以下のレプリカセットの例を参照ください。

  • "username"

    ホスト名に含めるかわりに、ユーザー名をここで指定することができます。 ユーザー名に ":" を含む場合などに特に便利です。 ホスト名で設定したユーザー名を上書きします。

  • "password"

    ホスト名に含めるかわりに、パスワードをここで指定することができます。 パスワードに "@" を含む場合などに特に便利です。 ホスト名で設定したパスワードを上書きします。

  • "db"

    ホスト名に含めるかわりに、認証対象のデータベースをここで指定することができます。 ホスト名で設定したデータベースを上書きします。

返り値

新しいデータベース接続オブジェクトを返します。

エラー / 例外

指定したすべてのホスト名へのデータベースへの接続に失敗した場合に MongoConnectionException をスローします。 指定したユーザー名やパスワードが間違っている場合にも MongoConnnectionException をスローします。 一般的な例外とその原因については MongoConnectionException のドキュメントを参照ください。

変更履歴

バージョン 説明
1.2.0

persist オプションが削除されました。すべての接続は持続的な接続となります。 今でも使うことはできますが、何の影響も及ぼしません。

"persist"

持続的な接続を行うかどうか。これを設定すると、接続が持続的なものとなります。 文字列の値を接続 ID として使うので、 array("persist" => "foobar") で初期化した Mongo のインスタンスがふたつあれば、 それは同じデータベース接続をあらわします。一方、 array("persist" => "barbaz") で初期化したインスタンスは別のデータベース接続を使います。

"replicaSet" パラメータは、boolean ではなく文字列を受け取るようになりました (しかし、今でも boolean で指定することはできます)。

1.0.2 コンストラクタがオプションの配列を受け取るようになりました。 以前のバージョンでは、コンストラクタは以下のパラメータを受け取っていました。
server

サーバー名。

connect

オプションの boolean パラメータで、 コンストラクタがデータベースに接続するかどうかを示します。 デフォルトは TRUE です。

persistent

持続的な接続を行うかどうか。

paired

ペア接続を行うかどうか。

1.0.9 replicaSet オプションが追加されました。
1.2.0 username および password オプションが追加されました。

例1 Mongo::__construct() でのレプリカセットの例

この例は、レプリカセットに接続する方法を示します。 このでは、次の三つのサーバー sf1.example.com、sf2.example.com および ny1.example.com があるものと仮定します。 マスタは、これらのうちのいずれかひとつとなります。

<?php

// カンマ区切りのサーバー名をコンストラクタに渡します
$m1 = new Mongo("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

// ひとつのシードを渡すだけで、ドライバがそこから完全なリストを取得して
// シードからマスタを探します
$m2 = new Mongo("mongodb://ny1.example.com", array("replicaSet" => "myReplSet"));

?>

現在のマスタで処理に失敗した場合、 セカンダリサーバーのうちのどれを新しいマスタにするかをドライバが判断し、 自動的にその接続を開始させます。この自動フェイルオーバー機能は、 replicaSet を指定しなければ正しく動作しません。

シードリストの中の少なくともひとつのシードに接続できなければ、 ドライバからレプリカセットに接続することはできません。

二つの別のレプリカセットからのシードを指定した場合の挙動は未定義です。

レプリカセットに関する詳細な情報は » コアドキュメント を参照ください。

例2 ドメインソケットへの接続

バージョン 1.0.9 以降では、ローカルで実行している MongoDB への接続に UNIX ドメインソケットを使えるようになりました。これは、 ネットワーク経由で接続するよりもわずかに高速です。

バージョン 1.5.0 では、MongoDB サーバーは自動的に /tmp/mongodb-<port>.sock でソケットをオープンします。 ここに接続するには、接続文字列でこのパスを指定します。

<?php

// MongoDB サーバーが、ローカルのポート 20000 で起動しています
$m = new Mongo("mongodb:///tmp/mongodb-20000.sock");

?>

これは、その他の接続とも組み合わせることができます。

<?php

// まずドメインソケットに接続し、失敗したときにはローカルホストへの接続を使います
$m = new MongoDB("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

例3 Mongo::__construct() での認証の例

認証を使うには、admin データベースにユーザーが存在しなければなりません。 Mongo シェルでユーザーを作るには、次のようにします。

> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
        "_id" : ObjectId("4b21272fd9ab21611d19095c"),
        "user" : "testUser",
        "pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>

ユーザーを作ったら、このユーザー名 "testUser" とパスワード "testPass" で次のようにして認証させることができます。

<?php

$m 
= new Mongo("mongodb://testUser:testPass@localhost");

?>


Mongo::dropDB> <Mongo::connectUtil
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes Mongo::__construct
sonic1000 at gmx dot de 09-Mar-2012 12:46
Please note, that somehow MongoDB will throw an Exception if you try to connect to a string like mongodb://A,B,C and one of the repsets is in revover mode:

_id" : 0,
"name" : "A:27017",
"health" : 1,
"state" : 3,
"stateStr" : "RECOVERING"
Niek at sourcebox dot nl 17-Feb-2012 12:01
After a big crash on our mongo database replica-set we started to investigate why PHP hangs itself when a server seems to disappear. It seems that this library isn't doing a very good job with connecting to a replicate set.

In the official mongo manual it says:
"The driver then connects to all servers on the seed list, perhaps in parallel to minimize connect time .." PHP doesn't do parallel. It tries every seed from the list one at the time. After one fails it goes to the next etc. This is how PHP works and i doubt it can be altered. So the problem starts when you connect like:
new Mongo("mongodb://192.168.0.100,192.168.0.101", array("replicaSet" => "myReplicaSet"));

When the server 192.168.0.100 crashes, all new connections will take at least 20 seconds (20 seconds connection timeout) before it moves to the second server. The webserver will come crashing down with all these hanging PHP instances. (If the server is still up though only the mongo service is down everything does continue to work without the delay though.)

The timeout setting will remedy a bit of this behavior making the connection like: (100 ms timeout)
new Mongo("mongodb://192.168.0.100,192.168.0.101", array("replicaSet" => "myReplicaSet", "timeout" => 100));
All new connections have a additional delay of 100 ms when there is a server crash which is better then the 20000 ms default value. Still not perfect but workable.

This behavior isn't really excepted when reading the manuals and people may think they have an failover mongo. This isn't the case when you are not using the timeout property.
Sid 20-Sep-2011 04:06
Well it looks like specifying the username, and password as an option in the option array DOES NOT work with replica sets properly.  I got a bunch of unauthorized exceptions when trying to do inserts.  Best bet is to specify username and password via the connection string.
rob at limeworks dot com dot au 02-Sep-2011 11:14
Note that even if you authenticate with a database specific user during instantiation of the Mongo class, it's still necessary to select the database before you try and use it.

Might sound common sense, but hopefully it will help someone anyway :D
Julius 04-Aug-2011 12:33
It's worth noting that authentication is not available in replicaSet with sharding before MongoDB version 1.9.1

http://www.mongodb.org/display/DOCS/Security+and+Authentication
arie grapa 13-Apr-2011 01:49
you can set mongo.auto_reconnect=1 in php.ini to cause it to automatically reconnect. This might be the default in future versions
Arkadiy Kukarkin 06-May-2010 11:17
The behavior of persistent connections is somewhat mysterious, but it appears that they remain for the duration of the process with some internal timeout value, and not until the end of script execution as you might expect based on the wording here and in close().

That is, the connection will remain open even once every object that used it is out of scope and can be accessed again with the persist key. This is consistent with the way e.g. DBI does things, but still somewhat confusing when not made explicit. A related issue is that under certain conditions php seems to open multiple connections even using the same key, but that's more of a bug report.
cap at unagon dot com 26-Feb-2010 11:38
Be sure *not* to append a slash at the end of the mongo URL.

$m = new Mongo("mongodb://dbuser:dbpasswd@localhost/");

in my case led to an empty web page and complete crash of the PHP interpreter, no chance to catch this as an exception.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites