Mongo
在线手册:中文 英文
PHP手册

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__constructCreates a new database connection object

说明

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

If no parameters are passed, this connects to "localhost:27017" (or whatever was specified in php.ini for mongo.default_host and mongo.default_port).

server should have the form:

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

The connection string always starts with mongodb://, to indicate it is a connection string in this form.

If username and password are specified, the constructor will attempt to authenticate the connection with the database before returning. Username and password are optional and must be followed by an @, if specified.

At least one host must be given (port optional, always defaulting to 27017) and as many hosts as desired may be connected to. Host names are comma-separated and the constructor will return successfully if it connected to at least one host. If it could not connect to any of the hosts, it will throw a MongoConnectionException.

Finally, if you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

参数

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "connect"

    If the constructor should connect before returning. Default is TRUE.

  • "timeout"

    For how long the driver should try to connect to the database (in milliseconds).

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the master will be determined by using the ismaster database command on the seeds, so the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

  • "username"

    The username can be specified here, instead of including it in the host list. This is especially useful if a username has a ":" in it. This overrides a username set in the host list.

  • "password"

    The password can be specified here, instead of including it in the host list. This is especially useful if a password has a "@" in it. This overrides a password set in the host list.

  • "db"

    The database to authenticate against can be specified here, instead of including it in the host list. This overrides a database given in the host list.

返回值

Returns a new database connection object.

错误/异常

Throws MongoConnectionException if it tries and fails to connect to the database for all hostnames given. It will also throw a MongoConnnectionException if an invalid username or password is given. See MongoConnectionException documentation for common exceptions and their causes.

更新日志

版本 说明
1.2.0

Removed the persist option, as all connections are now persistent. It can still be used, but it doesn't affect anything.

"persist"

If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an id for the connection, so two instances of Mongo that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection.

The "replicaSet" parameter now takes a string, not a boolean (although boolean is still accepted).

1.0.2 Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters:
server

The server name.

connect

Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE.

persistent

If the connection should be persistent.

paired

If the connection should be paired.

1.0.9 Added the replicaSet option.
1.2.0 Added the username and password options.

范例

Example #1 Mongo::__construct() replica set example

This example shows how to connect the driver to a replica set. It assumes that there is a set of three servers: sf1.example.com, sf2.example.com, and ny1.example.com. The master could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
$m1 = new Mongo("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

// you only need to pass a single seed, the driver will derive the full list and
// find the master from this seed
$m2 = new Mongo("mongodb://ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current master fails, the driver will figure out which secondary server became the new master and automatically start using that connection. Automatic failover will not work correctly if replicaSet is not specified.

At least one seed in the seed list must be up for the driver to connect to the replica set.

If you include seeds from two separate replica sets, behavior is undefined.

See the » core documentation on replica sets for more information.

Example #2 Connecting to a domain socket

In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection.

In version 1.5.0, the MongoDB server automatically opens a socket at /tmp/mongodb-<port>.sock. You can connect to this by specifying the path in your connection string:

<?php

// MongoDB server running locally on port 20000
$m = new Mongo("mongodb:///tmp/mongodb-20000.sock");

?>

You can combine this with any other connections you'd like:

<?php

// try to connect to the domain socket, fall back to localhost connection
$m = new MongoDB("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Example #3 Mongo::__construct() authentication example

A user must exist in the admin database before attempting to use authentication. You can create one with the Mongo shell by running:

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

After creating a user with, in this case, username "testUser" and password "testPass", you can create an authenticated connection:

<?php

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

?>

Mongo
在线手册:中文 英文
PHP手册
PHP手册 - N: Creates a new database connection object

用户评论:

sonic1000 at gmx dot de (08-Mar-2012 11: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 (16-Feb-2012 11: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 03: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 10: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 11: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 12: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 10: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 10: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.