php-doc-en/reference/mongo/mongoclient/construct.xml

656 lines
21 KiB
XML

<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="mongoclient.construct" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>MongoClient::__construct</refname>
<refpurpose>Creates a new database connection object</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<constructorsynopsis>
<modifier>public</modifier> <methodname>MongoClient::__construct</methodname>
<methodparam choice="opt"><type>string</type><parameter>server</parameter><initializer>"mongodb://localhost:27017"</initializer></methodparam>
<methodparam choice="opt"><type>array</type><parameter>options</parameter><initializer>array("connect" => &true;)</initializer></methodparam>
</constructorsynopsis>
<para>
If no parameters are passed, this connects to "localhost:27017" (or whatever
was specified in php.ini for
<link linkend="ini.mongo.default-host">mongo.default_host</link> and
<link linkend="ini.mongo.default-port">mongo.default_port</link>).
</para>
<para>
<parameter>server</parameter> should have the form:
<programlisting>
<![CDATA[
mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db
]]>
</programlisting>
</para>
<para>
The connection string always starts with <literal>mongodb://</literal>, to
indicate it is a connection string in this form.
</para>
<para>If <literal>username</literal> and <literal>password</literal>
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 <literal>@</literal>, if specified.
</para>
<para>
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 <classname>MongoConnectionException</classname>. Please see the
<link linkend="mongo.connecting.rs">Replica Sets</link> section for
information on how to connect to Replica Sets.
</para>
<para>
If you specified a username and password, you may specify a database to
authenticate with. If <literal>db</literal> is not specified, "admin" will
be used.
</para>
<para>
An optional query string may be used to specify extra options. The same
options are supported through the <parameter>options</parameter> array as
well, and are therefore redescribed there. See the <link
linkend="mongo.mongoclient.construct.examples">examples below</link> on
how to set those options.
</para>
<para>
One part of the options governs how the driver reads from secondary nodes
in a replica set environment. Extra information on how these read
preferences work is available as well through the <link
linkend="mongo.readpreferences">read preferences</link> documentation page.
</para>
</refsect1>
<refsect1 role="parameters" xml:id="mongo.mongoclient.construct.parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term>
<parameter>server</parameter>
</term>
<listitem>
<para>
The server name.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>options</parameter>
</term>
<listitem>
<para>
An array of options for the connection. Currently available options
include:
<itemizedlist>
<listitem>
<para>
<literal>"connect"</literal>
</para>
<para>
If the constructor should connect before returning. Default is
&true;. When set to &false; the driver will
<emphasis>automatically</emphasis> connection to the server whenever
it is necessary to do a query. Alternatively, you can run
<function>MongoClient::connect</function> manually.
</para>
<warning>
<para>
This option is not supported through the connection string.
</para>
</warning>
</listitem>
<listitem>
<para>
<literal>"connectTimeoutMS"</literal>
</para>
<para>
How long a connection can take to be opened before timing out.
</para>
</listitem>
<listitem>
<para>
<literal>"db"</literal>
</para>
<para>
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.
</para>
</listitem>
<listitem>
<para>
<literal>"fsync"</literal>
</para>
<para>
When <literal>fsync</literal> is set, all write operations on the
database will block until the database server has flushed its
database files to disk. This makes write operations a lot slower,
but it guarantees that the write operation has succeeded and
committed to disk. Please avoid <emphasis>using</emphasis> this
option and use the <literal>journal</literal> option instead,
perhaps in combination with the <literal>w</literal> option.
</para>
</listitem>
<listitem>
<para>
<literal>"journal"</literal>
</para>
<para>
When <literal>journal</literal> is set, all write operations on the
database will block until the database server has flushed the
journal to disk. This makes the write operations marginally slower,
but it guarantees that the write operation has succeeded and the
operation can be recovered in case of total system failure.
</para>
</listitem>
<listitem>
<para>
<literal>"password"</literal>
</para>
<para>
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.
</para>
</listitem>
<listitem>
<para>
<literal>"readPreference"</literal>
</para>
<para>
Specifies the read preference type. Read preferences provide you
with control from which secondaries data can be read from.
</para>
<para>
Allowed values are: <constant>MongoClient::RP_PRIMARY</constant>,
<constant>MongoClient::RP_PRIMARY_PREFERRED</constant>,
<constant>MongoClient::RP_SECONDARY</constant>,
<constant>MongoClient::RP_SECONDARY_PREFERRED</constant> and
<constant>MongoClient::RP_NEAREST</constant>.
</para>
<para>
See the documentation on <link linkend="mongo.readpreferences">read
preferences</link> for more information.
</para>
</listitem>
<listitem>
<para>
<literal>"readPreferenceTags"</literal>
</para>
<para>
Specifies the read preference tags as an array of strings. Tags can be
used in combination with the <literal>readPreference</literal> option
to further control which secondaries data might be read from.
</para>
<para>
See the documentation on <link linkend="mongo.readpreferences">read
preferences</link> for more information.
</para>
</listitem>
<listitem>
<para>
<literal>"replicaSet"</literal>
</para>
<para>
The name of the replica set to connect to. If this is given, the
primary will be automatically be determined. This means that the
driver may end up connecting to a server that was not even listed.
See the replica set example below for details.
</para>
</listitem>
<listitem>
<para>
<literal>"socketTimeoutMS"</literal>
</para>
<para>
How long a send or receive on a socket can take before timing out.
<note>
<simpara>
This is a client side timeout. If an <literal>insert</literal> hits
the <literal>"socketTimeoutMS"</literal> value there is no way to
know if the server actually received the write or not.
</simpara>
</note>
</para>
</listitem>
<listitem>
<para>
<literal>"username"</literal>
</para>
<para>
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.
</para>
</listitem>
<listitem>
<para>
<literal>"w"</literal>
</para>
<para>
The <literal>w</literal> option specifies the
<link linkend="mongo.writeconcerns">Write Concern</link> for the driver,
which determines how long the driver blocks when writing. The
default value is <literal>1</literal>.
</para>
<para>
This option is applicable when connecting to both single servers and
replica sets. A positive value controls how <emphasis>many</emphasis>
nodes must acknowledge the write instruction before the driver
continues. A value of <literal>1</literal> would require the single
server or primary (in a replica set) to acknowledge the write
operation. A value of <literal>3</literal> would cause the driver to
block until the write has been applied to the primary as well as two
secondary servers (in a replica set).
</para>
<para>
A string value is used to control which tag sets are taken into
account for write concerns. <literal>"majority"</literal> is special
and ensures that the write operation has been applied to the majority
(more than 50%) of the participating nodes.
</para>
</listitem>
<listitem>
<para>
<literal>"wTimeoutMS"</literal>
</para>
<para>
This option is used in combination with the <literal>"w"</literal>
option. It controls how many milliseconds the server waits for the
write concern to be satisfied. If it takes longer then the server
signals to the driver that it took too long and the driver will throw
a <classname>MongoCursorException</classname> exception.
</para>
</listitem>
</itemizedlist>
</para>
<para>
The following options are deprecated and should no longer be used:
<itemizedlist>
<listitem>
<para>
<literal>"timeout"</literal>
</para>
<para>
Deprecated alias for "connectTimeoutMS".
</para>
</listitem>
<listitem>
<para>
<literal>"wTimeout"</literal>
</para>
<para>
Deprecated alias for "wTimeoutMS".
</para>
</listitem>
</itemizedlist>
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns a new database connection object.
</para>
</refsect1>
<refsect1 role="errors">
&reftitle.errors;
<para>
Throws <classname>MongoConnectionException</classname> if it tries and fails
to connect to the database for all hostnames given. It will also throw a
<classname>MongoConnnectionException</classname> if an invalid username or
password is given. See <classname>MongoConnectionException</classname>
documentation for common exceptions and their causes.
</para>
</refsect1>
<refsect1 role="examples" xml:id="mongo.mongoclient.construct.examples">
&reftitle.examples;
<example>
<title><function>MongoClient::__construct</function> replica set example</title>
<para>
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 primary could be any one of these servers.
</para>
<programlisting role="php">
<![CDATA[
<?php
// pass a comma-separated list of server names to the constructor
// Note that we don't need to pass in all the members of the replicaset, the driver
// will derive the full list.
$m1 = new MongoClient("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));
?>
]]>
</programlisting>
<para>
If the current primary fails, the driver will figure out which secondary
server became the new primary and automatically start using that connection.
Automatic failover will not work correctly if <literal>replicaSet</literal>
is not specified.
</para>
<para>
At least one seed in the seed list must be up for the driver to connect to
the replica set.
</para>
<para>
If you include seeds from two separate replica sets, behavior is undefined.
</para>
<para>See the
<link xlink:href="&url.mongodb.dochub.rs;">core documentation</link> on
replica sets for more information.
</para>
</example>
<example>
<title>Connecting to a domain socket</title>
<para>
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.
</para>
<para>
In version 1.5.0, the MongoDB server automatically opens a socket at
/tmp/mongodb-&lt;port&gt;.sock. You can connect to this by specifying the
path in your connection string:
</para>
<programlisting role="php">
<![CDATA[
<?php
// MongoDB server running locally on port 20000
$m = new MongoClient("mongodb:///tmp/mongodb-20000.sock");
?>
]]>
</programlisting>
<para>
You can combine this with any other connections you'd like:
</para>
<programlisting role="php">
<![CDATA[
<?php
// try to connect to the domain socket, fall back to localhost connection
$m = new MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");
?>
]]>
</programlisting>
</example>
<example>
<title><function>MongoClient::__construct</function> authentication example</title>
<para>
A user must exist in the admin database before attempting to use
authentication. You can create one with the Mongo shell by running:
</para>
<programlisting>
<![CDATA[
> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
"_id" : ObjectId("4b21272fd9ab21611d19095c"),
"user" : "testUser",
"pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>
]]>
</programlisting>
<para>
After creating a user with, in this case, username "testUser" and password
"testPass", you can create an authenticated connection:
</para>
<programlisting role="php">
<![CDATA[
<?php
$m = new MongoClient("mongodb://testUser:testPass@localhost");
?>
]]>
</programlisting>
</example>
<example>
<title><function>MongoClient::__construct</function> read preference example</title>
<programlisting role="php">
<![CDATA[
<?php
// Prefer the nearest server in the "east" data center
$uri = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
]]>
</programlisting>
<para>
See the <link linkend="mongo.readpreferences">read preferences</link>
section of this manual for further information.
</para>
</example>
<example>
<title><function>MongoClient::__construct</function> options example</title>
<para>
Options can be passed both through the query string in the connection
string, or as an array passed as second argument to the constructor.
</para>
<para>
Here we set the journal option to true and readPreference to secondary
preferred as default for all write operations:
</para>
<programlisting>
<![CDATA[
<?php
$m = new MongoClient("mongodb://localhost/?journal=true&readPreference=secondary");
?>
]]>
</programlisting>
<para>
And now we do the same, but as an options array:
</para>
<programlisting>
<![CDATA[
<?php
$options = array(
'journal' => true,
'readPreference' => 'secondary',
);
$m = new MongoClient("mongodb://localhost/", $options);
?>
]]>
</programlisting>
</example>
<example>
<title><function>MongoClient::__construct</function> read preference example</title>
<programlisting role="php">
<![CDATA[
<?php
// Prefer the nearest server in the "east" data center
$uri = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
]]>
</programlisting>
<para>
See the <link linkend="mongo.readpreferences">read preferences</link>
section of this manual for further information.
</para>
</example>
</refsect1>
<refsect1 role="changelog">
&reftitle.changelog;
<para>
<informaltable>
<tgroup cols="2">
<thead>
<row>
<entry>&Version;</entry>
<entry>&Description;</entry>
</row>
</thead>
<tbody>
<row>
<entry>1.4.0</entry>
<entry>
<para>
Added the <literal>"wTimeoutMS"</literal> option has replacement
for <literal>"wTimeout"</literal>.
</para>
</entry>
</row>
<row>
<entry>1.3.4</entry>
<entry>
<para>
Added the <literal>"connectTimeoutMS"</literal> and
<literal>"socketTimeoutMS"</literal> options.
</para>
</entry>
</row>
<row>
<entry>1.3.0</entry>
<entry>
<para>
Added the <literal>"readPreference"</literal>,
<literal>"readPreferenceTags"</literal>, <literal>"w"</literal> and
<literal>"wTimeout"</literal> options.
</para>
</entry>
</row>
<row>
<entry>1.2.0</entry>
<entry>
<para>
Added the <literal>"username"</literal> and
<literal>"password"</literal> options.
</para>
<para>
Removed the <literal>"persist"</literal> option, as all connections are
now persistent. It can still be used, but it doesn't affect anything.
</para>
<variablelist>
<varlistentry>
<term>
<parameter>"persist"</parameter>
</term>
<listitem>
<para>
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
<classname>MongoClient</classname> that are initialized with
<literal>array("persist" => "foobar")</literal> will share the same
database connection, whereas an instance initialized with
<literal>array("persist" => "barbaz")</literal> will use a different
database connection.
</para>
</listitem>
</varlistentry>
</variablelist>
<para>
The <literal>"replicaSet"</literal> option now takes a string, not a
boolean.
</para>
</entry>
</row>
<row>
<entry>1.0.9</entry>
<entry>Added the <literal>"replicaSet"</literal> option.</entry>
</row>
<row>
<entry>1.0.2</entry>
<entry>
<para>
Changed constructor to take an array of options. Pre-1.0.2, the
constructor took the following parameters:
</para>
<variablelist>
<varlistentry>
<term>
<parameter>server</parameter>
</term>
<listitem>
<para>
The server name.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>connect</parameter>
</term>
<listitem>
<para>
Optional boolean parameter specifying if the constructor should
connect to the database before returning. Defaults to &true;.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>persistent</parameter>
</term>
<listitem>
<para>
If the connection should be persistent.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>paired</parameter>
</term>
<listitem>
<para>
If the connection should be paired.
</para>
</listitem>
</varlistentry>
</variablelist>
</entry>
</row>
</tbody>
</tgroup>
</informaltable>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->