added connection pool functions

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@312738 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Kristina Chodorow 2011-06-30 22:20:49 +00:00
parent 84f749b644
commit 63c5351f88
8 changed files with 489 additions and 340 deletions

View file

@ -5,8 +5,8 @@
<title>Connecting</title>
<para>
Connecting to MongoDB can be as easy as <literal>new Mongo</literal>, but
there are many additional options and configurations. The
Connecting to MongoDB can be as easy as <literal>new Mongo</literal>, but
there are many additional options and configurations. The
<function>Mongo::__construct</function> page covers all of the API options,
but this page gives some more details and advice for practical use cases.
</para>
@ -14,9 +14,27 @@
<section>
<title>Logging In on Connection</title>
<para>
If MongoDB is started with the <literal>--auth</literal> option, connections
must be authenticated before they are used. You can do this on a
per-database level with <function>MongoDB::authenticate</function>:
If MongoDB is started with the <literal>--auth</literal> or
<literal>--keyFile</literal> options, you must log in before you can do any
operations with the driver. You can log in on connection by supplying the
username and password in the connection URI:
</para>
<programlisting role="php">
<![CDATA[
<?php
$m = new Mongo("mongodb://${username}:${password}@localhost");
?>
]]>
</programlisting>
<para>
If your connection is dropped, the driver will automatically attempt to
reconnect and reauthenticate you.
</para>
<para>
You can also authenticate on a per-database level with
<function>MongoDB::authenticate</function>:
</para>
<programlisting role="php">
<![CDATA[
@ -35,27 +53,10 @@ $db->authenticate($username, $password);
dropped and then reconnected, the connection will no longer be authenticated.
</para>
<para>
If you use the connection string format described by
<function>Mongo::__construct</function>, the database will authenticate on
connection and reauthenticate if the connection is re-established.
</para>
<para>
This is equivalent to the code above, except that reconnections to the
database will be authenticated automatically:
</para>
<programlisting role="php">
<![CDATA[
<?php
$m = new Mongo("mongodb://${username}:${password}@localhost");
?>
]]>
</programlisting>
<para>
By default, the driver will authenticate the user against the admin database.
To authenticate with a different database, specify the database name after
the hosts. This example will log the user into the "blog" database:
If you use the URI format, the driver will authenticate the user against the
admin database. To authenticate with a different database, specify the
database name after the hosts. This example will log the user into the
"blog" database:
</para>
<programlisting role="php">
<![CDATA[
@ -78,121 +79,52 @@ $m = new Mongo("mongodb://${username}:${password}@localhost/blog");
<![CDATA[
<?php
$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => true));
$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => "myReplSetName"));
?>
]]>
</programlisting>
<para>
Version 1.0.9+ of the driver is required to connect to a replica set
(earlier versions of the driver will not autodetect the master or reconnect
Version 1.0.9+ of the driver is required to connect to a replica set
(earlier versions of the driver will not autodetect the master or reconnect
correctly).
</para>
<para>
The PHP driver will query the database server(s) listed to figure out who is
master. So long as it can connect to at least one host listed and find a
master. So long as it can connect to at least one host listed and find a
master, the connection will succeed. If it cannot make a connection to any
servers listed or cannot find a master, a
servers listed or cannot find a master, a
<classname>MongoConnectionException</classname> will be thrown.
</para>
<para>
If the master becomes unavailable, the slaves will not promote a new master
for a few seconds. During that time, this connection will not be able to
If the master becomes unavailable, the slaves will not promote a new master
for a few seconds. During that time, this connection will not be able to
perform any database operations (connections to slaves will still be able to
perform reads). Thus, if you attempt to do any sort of read or write on this
connection, it will throw an exception.
</para>
<para>
Once a master is elected, attempting to perform a read or write will allow
the driver to detect the new master. The driver will make this its primary
Once a master is elected, attempting to perform a read or write will allow
the driver to detect the new master. The driver will make this its primary
database connection and continue operating normally.
</para>
<para>
For more information on replica sets, see the
For more information on replica sets, see the
<link xlink:href="&url.mongodb.replica;">core documentation</link>.
</para>
</section>
<section>
<title>Persistent Connections</title>
<para>
Creating new connection to the database is very slow. To minimize the number
of connections that you need to make, you can use persistent connections. A
persistent connection is saved by PHP, so you can use the same connection for
multiple requests.
</para>
<para>
For example, this simple program connects to the database 1000 times:
</para>
<programlisting role="php">
<![CDATA[
<?php
for ($i=0; $i<1000; $i++) {
$m = new Mongo();
}
?>
]]>
</programlisting>
<para>
It takes approximately 18 seconds to execute. If we change it to use a
persistent connection:
</para>
<programlisting role="php">
<![CDATA[
<?php
for ($i=0; $i<1000; $i++) {
$m = new Mongo("localhost:27017", array("persist" => "x"));
}
?>
]]>
</programlisting>
<para>
...it takes less than .02 seconds to execute, as it only makes one database
connection.
</para>
<para>
Persistent connections need an identifier string (which is "x" in the above
example) to uniquely identify them. For a persistent connection to be used,
the hostname, port, persist string, and username and password (if given) must
match an existing persistent connection. Otherwise, a new connection will be
created with this identifying information.
</para>
<para>
Persistent connections are <emphasis>highly recommended</emphasis> and should
always be used in production unless there is a compelling reason not to.
Most of the reasons that they are not recommended for relational databases
are irrelevant to MongoDB.
</para>
<para>
Persistent connections will become the default connection type in 1.0.12. To
create a non-persistent connection, you will need to pass
<literal>"persist" =&gt; false</literal> to
<function>Mongo::__construct</function>.
</para>
</section>
<section>
<title>Domain Socket Support</title>
<para>
If you are running MongoDB locally and have version 1.0.9 or better of the
If you are running MongoDB locally and have version 1.0.9 or better of the
driver, you can connect to the database via file. MongoDB automatically
opens a socket file on startup: /tmp/mongodb-&lt;port&gt;.sock.
</para>
<para>
To connect to the socket file, specify the path in your MongoDB connection
To connect to the socket file, specify the path in your MongoDB connection
string:
</para>
@ -224,4 +156,93 @@ $m = new Mongo("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");
</section>
<section>
<title>Connection Pooling</title>
<para>
In version 1.2.0+, the driver will automatically manage connection pools for
the user.
</para>
<para>
When a user creates a new instance of <classname>Mongo</classname>, all
necessary connections will be taken from their pools (replica set connections
may require multple connections). When the <classname>Mongo</classname>
instance goes out of scope, the connections will be returned to the pool.
</para>
</section>
<section>
<title>Persistent Connections</title>
<note>
<para>
This section is not relevant for 1.2.0+. In 1.2.0+, connections are always
persistent and managed automatically by the driver.
</para>
</note>
<para>
Creating new connection to the database is very slow. To minimize the number
of connections that you need to make, you can use persistent connections. A
persistent connection is saved by PHP, so you can use the same connection for
multiple requests.
</para>
<para>
For example, this simple program connects to the database 1000 times:
</para>
<programlisting role="php">
<![CDATA[
<?php
for ($i=0; $i<1000; $i++) {
$m = new Mongo();
}
?>
]]>
</programlisting>
<para>
It takes approximately 18 seconds to execute. If we change it to use a
persistent connection:
</para>
<programlisting role="php">
<![CDATA[
<?php
for ($i=0; $i<1000; $i++) {
$m = new Mongo("localhost:27017", array("persist" => "x"));
}
?>
]]>
</programlisting>
<para>
...it takes less than .02 seconds to execute, as it only makes one database
connection.
</para>
<para>
Persistent connections need an identifier string (which is "x" in the above
example) to uniquely identify them. For a persistent connection to be used,
the hostname, port, persist string, and username and password (if given) must
match an existing persistent connection. Otherwise, a new connection will be
created with this identifying information.
</para>
<para>
Persistent connections are <emphasis>highly recommended</emphasis> and should
always be used in production unless there is a compelling reason not to.
Most of the reasons that they are not recommended for relational databases
are irrelevant to MongoDB.
</para>
<para>
Persistent connections will become the default connection type in 1.0.12. To
create a non-persistent connection, you will need to pass
<literal>"persist" =&gt; false</literal> to
<function>Mongo::__construct</function>.
</para>
</section>
</section>

View file

@ -15,13 +15,8 @@
</methodsynopsis>
<para>
This method can only be used with a connection to a replica set. It returns
the status of all of the hosts in the set and updates the connection
information (the updating is invisible to the user).
</para>
<para>
This is called automatically by the driver every five seconds.
This method can only be used with a connection to a replica set. It returns
the status of all of the hosts in the set.
</para>
<para>
@ -39,98 +34,54 @@
&reftitle.returnvalues;
<para>
Returns an array of information about the hosts in the set. Includes each
host's hostname, id in the set, health (1 is healthy), the uptime, and how
up-to-date the host is compared to the primary. For example, on a
three-member replica set running locally, it might look something like:
host's hostname, its health (1 is healthy), its state (1 is primary, 2 is
secondary, 0 is anything else), the amount of time it took to ping the
server, and when the last ping occurred. For example, on a three-member
replica set, it might look something like:
</para>
<screen>
<![CDATA[
Array
(
[ubuntu:27017] => Array
(
[_id] => 0
[name] => ubuntu:27017
[health] => 1
[state] => 1
[stateStr] => PRIMARY
[optime] => MongoTimestamp Object
(
[sec] => 1
[inc] => 1291155754
)
[optimeDate] => MongoDate Object
(
[sec] => 1291155754
[usec] => 0
)
[self] => 1
)
[ubuntu:27019] => Array
(
[_id] => 2
[name] => ubuntu:27019
[health] => 1
[state] => 2
[stateStr] => SECONDARY
[uptime] => 91928
[optime] => MongoTimestamp Object
(
[sec] => 1
[inc] => 1291155754
)
[optimeDate] => MongoDate Object
(
[sec] => 1291155754
[usec] => 0
)
[lastHeartbeat] => MongoDate Object
(
[sec] => 1291158846
[usec] => 0
)
)
[ubuntu:27018] => Array
(
[_id] => 1
[name] => ubuntu:27018
[health] => 1
[state] => 2
[stateStr] => SECONDARY
[uptime] => 91944
[optime] => MongoTimestamp Object
(
[sec] => 1
[inc] => 1291155754
)
[optimeDate] => MongoDate Object
(
[sec] => 1291155754
[usec] => 0
)
[lastHeartbeat] => MongoDate Object
(
[sec] => 1291158846
[usec] => 0
)
)
)
array(2) {
["A:27017"]=>
array(4) {
["health"]=>
int(1)
["state"]=>
int(2)
["ping"]=>
int(369)
["lastPing"]=>
int(1309470644)
}
["B:27017"]=>
array(4) {
["health"]=>
int(1)
["state"]=>
int(1)
["ping"]=>
int(139)
["lastPing"]=>
int(1309470644)
}
["C:27017"]=>
array(4) {
["health"]=>
int(1)
["state"]=>
int(2)
["ping"]=>
int(1012)
["lastPing"]=>
int(1309470644)
}
}
]]>
</screen>
<para>
This returns &null; if the connection is not connected to a replica set or
has not been initialized, yet.
In the example above, B and C are secondaries (state 2). B is likely to be
selected for queries if slaveOkay is set, as it has a lower ping time (and
thus is likely closer or handling less load) than C.
</para>
</refsect1>
</refentry>
@ -152,4 +103,4 @@ End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
-->

View file

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="mongo.getpoolsize" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>Mongo::getPoolSize</refname>
<refpurpose>Get pool size for connection pools</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<modifier>public</modifier> <type>int</type><methodname>Mongo::getPoolSize</methodname>
<void/>
</methodsynopsis>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
&no.function.parameters;
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns the current pool size.
</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
-->

View file

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="mongo.pooldebug" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>Mongo::poolDebug</refname>
<refpurpose>Returns information about all connection pools.</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<modifier>public</modifier> <type>array</type><methodname>Mongo::poolDebug</methodname>
<void/>
</methodsynopsis>
<para>
Returns an array of information about all connection pools.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
&no.function.parameters;
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Each connection pool has an identifier, which starts with the host. For each
pool, this function shows the following fields:
<variablelist>
<varlistentry>
<term>
<parameter>in use</parameter>
</term>
<listitem>
<para>
The number of connections currently being used by
<classname>Mongo</classname> instances.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>in pool</parameter>
</term>
<listitem>
<para>
The number of connections currently in the pool (not being used).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>remaining</parameter>
</term>
<listitem>
<para>
The number of connections that could be created by this pool. For
example, suppose a pool had 5 connections remaining and 3 connections in
the pool. We could create 8 new instances of
<classname>Mongo</classname> before we exhausted this pool (assuming no
instances of <classname>Mongo</classname> went out of scope, returning
their connections to the pool).
</para>
<para>
A negative number means that this pool will spawn unlimited connections.
</para>
<para>
Before a pool is created, you can change the max number of connections by
calling <function>Mongo::setPoolSize</function>. Once a pool is showing
up in the output of this function, its size cannot be changed.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<parameter>timeout</parameter>
</term>
<listitem>
<para>
The socket timeout for connections in this pool. This is how long
connections in this pool will attempt to connect to a server before
giving up.
</para>
</listitem>
</varlistentry>
</variablelist>
</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
-->

View file

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision$ -->
<refentry xml:id="mongo.setpoolsize" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<refnamediv>
<refname>Mongo::setPoolSize</refname>
<refpurpose>Set the size for future connection pools.</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<modifier>public</modifier> <type>bool</type><methodname>Mongo::setPoolSize</methodname>
<methodparam><type>int</type><parameter>size</parameter></methodparam>
</methodsynopsis>
<para>
Sets the max number of connections new pools will be able to create.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term>
<parameter>size</parameter>
</term>
<listitem>
<para>
The max number of connections future pools will be able to create.
Negative numbers mean that the pool will spawn an infinite number of
connections.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
Returns the former value of pool size.
</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
-->

View file

@ -11,7 +11,7 @@
<para>
If you are using a
<link xlink:href="&url.mongodb.replica;">replica set</link> and version
1.1.0 or above of the driver, the driver can automatically route reads to
1.1.0 or above of the driver, the driver can automatically route reads to
slaves. This behavior does not exist in earlier versions of the driver and
<emphasis>cannot</emphasis> be used with "normal" master-slave.
</para>
@ -20,10 +20,10 @@
<para>
By default, the driver will send all queries to the master. If you set the
"slaveOkay" option, the driver will send all queries to a non-primary server,
if possible. The "slaveOkay" option can be set at every "level":
if possible. The "slaveOkay" option can be set at every "level":
<link linkend="mongo.setslaveokay">connection</link>,
<link linkend="mongodb.setslaveokay">database</link>,
<link linkend="mongocollection.setslaveokay">collection</link>, and
<link linkend="mongodb.setslaveokay">database</link>,
<link linkend="mongocollection.setslaveokay">collection</link>, and
<link linkend="mongocursor.slaveokay">cursor</link>. Each class inherits the
"slaveOkay" setting from the class above it, so if you do:
</para>
@ -43,7 +43,7 @@ $cursor = $c->find();
<para>
then the query will be executed against a slave (the collection inherited
"slaveOkay" from the database and the cursor inherited it from the
"slaveOkay" from the database and the cursor inherited it from the
collection).
</para>
@ -51,21 +51,23 @@ $cursor = $c->find();
<title>How slaves are chosen</title>
<para>
Each instance of <classname>Mongo</classname> gets its own slave, randomly
chosen from the readable slaves. This holds, even if you are using
persistent connections. So, if we do something like:
Each instance of <classname>Mongo</classname> chooses its own slave using
the available slave with the lowest ping time. So, if we had a PHP client
in Europe and one in Australia and we had one secondary in each of these
data centers, we could do:
</para>
<programlisting role="php">
<![CDATA[
<?php
// connects to a replica set with members ip0, ip1, and ip2
// ip0 is the primary, ip1 and ip2 are secondaries
$m1 = new Mongo("mongodb://ip0", array("replicaSet" => true, "persist" => "x"));
// P is the primary
// on the Australian client
$m1 = new Mongo("mongodb://P", array("replicaSet" => true));
echo "m1's slave is ".$m1->getSlave()."\n";
// uses the same connection as $m1
$m2 = new Mongo("mongodb://ip0", array("replicaSet" => true, "persist" => "x"));
// on the European client
$m2 = new Mongo("mongodb://P", array("replicaSet" => true));
echo "m2's slave is ".$m2->getSlave()."\n";
?>
@ -75,80 +77,28 @@ echo "m2's slave is ".$m2->getSlave()."\n";
we'd probably end up with something like:
</para>
<screen>
m1's slave is: ip2
m2's slave is: ip1
m1's slave is: australianHost
m2's slave is: europeanHost
</screen>
<para>
If we continued to create new <classname>Mongo</classname>s, we should get a
fairly even distribution between ip1 and ip2. Keep in mind that all
secondaries listed by the <function>isMaster</function> command will be in
the pool of possible readers (even ones with priority 0 or slaveDelay set).
If you have certain servers you do not wish to read from, either route reads
manually or add the hidden option to the server's replica set configuration.
</para>
<para>
Slaves are chosen on a per-instance basis and do no change (unless something
bad happens to your set and they are forced to).
</para>
<para>
You can see what the driver thinks is the current status of the set members
by running <function>Mongo::getHosts</function>.
</para>
<para>
If no non-primary server is readable, the driver will send
reads to the primary (even if "slaveOkay" is set). A server is considered
readable if its state is 2 (SECONDARY) and its health is 1. You can check
this with <function>Mongo::getHosts</function> (some fields omitted for
clarity):
</para>
<programlisting>
<![CDATA[
Array
(
[ubuntu:27017] => Array
(
[_id] => 0
[name] => ip0
[health] => 1
[state] => 1
[stateStr] => PRIMARY
)
[ubuntu:27019] => Array
(
[_id] => 2
[name] => ip1
[health] => 1
[state] => 2
[stateStr] => SECONDARY
)
[ubuntu:27018] => Array
(
[_id] => 1
[name] => ip2
[health] => 1
[state] => 2
[stateStr] => SECONDARY
)
)
]]>
</programlisting>
<para>
The set above has two readable servers, "ip1" and "ip2". If both of
these went down or became stale, reads would go to "ip0".
If no non-primary server is readable, the driver will send
reads to the primary (even if "slaveOkay" is set). A server is considered
readable if its state is 2 (SECONDARY) and its health is 1. You can check
this with <function>Mongo::getHosts</function>.
</para>
<para>
If you enjoy twiddling knobs that you probably shouldn't mess with, you can
force the driver to use a different slave by calling
<function>Mongo::switchSlave</function>. This randomly chooses a new slave
to use and shouldn't be used unless you know what you're doing.
If you enjoy twiddling knobs that you probably shouldn't mess with, you can
request the driver to use a different slave by calling
<function>Mongo::switchSlave</function>. This may choose a new slave
(if one is available) and shouldn't be used unless you know what you're
doing.
</para>
</section>
@ -156,19 +106,18 @@ Array
<title>Random notes</title>
<para>
Writes are always sent to the primary. Database commands, even read-only
Writes are always sent to the primary. Database commands, even read-only
commands, are also always sent to the primary.
</para>
<para>
The health and state of a slave is checked every 5 seconds or when the next
operation occurs after 5 seconds. It will also recheck the configuration
when the driver has a problem reaching a server. You can manually force the
driver to update the status by calling <function>Mongo::getHosts</function>.
The health and state of a slave is checked every 5 seconds or when the next
operation occurs after 5 seconds. It will also recheck the configuration
when the driver has a problem reaching a server.
</para>
<para>
Note that a non-primary server may be behind the primary in operations, so
Note that a non-primary server may be behind the primary in operations, so
your application must be okay with getting out-of-date data (or you must use
w for all writes).
</para>
@ -202,10 +151,10 @@ $joe = $people->findOne(array("_id" => $person['_id']));
</programlisting>
</para>
<para>
Unless the user has specified otherwise, the _id field is a
<classname>MongoId</classname>. The most common mistake is attepting to use
a string to match a <classname>MongoId</classname>. Keep in mind that these
are two different datatypes, and will not match each other in the same way
Unless the user has specified otherwise, the _id field is a
<classname>MongoId</classname>. The most common mistake is attepting to use
a string to match a <classname>MongoId</classname>. Keep in mind that these
are two different datatypes, and will not match each other in the same way
that the string "array()" is not the same as an empty array. For example:
<programlisting role="php">
@ -232,11 +181,11 @@ $joe = $people->findOne(array("_id" => $pid));
<title>Arrays</title>
<para>
Arrays are special in a couple ways. First, there are two types that
Arrays are special in a couple ways. First, there are two types that
MongoDB uses: "normal" arrays and associative arrays. Associative arrays can
have any mix of key types and values. "Normal" arrays are defined as arrays
with ascending numeric indexes starting at 0 and increasing by one for each
element. These are, typically, just your usual PHP array.
have any mix of key types and values. "Normal" arrays are defined as arrays
with ascending numeric indexes starting at 0 and increasing by one for each
element. These are, typically, just your usual PHP array.
</para>
<para>
@ -255,8 +204,8 @@ $collection->save(array("awards" => array("gold", "silver", "bronze")));
</programlisting>
<para>
Queries can reach into arrays to search for elements. Suppose that we wish
to find all documents with an array element of a given value. For example,
Queries can reach into arrays to search for elements. Suppose that we wish
to find all documents with an array element of a given value. For example,
documents with a "gold" award, such as:
</para>
@ -265,9 +214,9 @@ $collection->save(array("awards" => array("gold", "silver", "bronze")));
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}
]]>
</programlisting>
<para>
This can be done with a simple query, ignoring the fact that "awards" is an
This can be done with a simple query, ignoring the fact that "awards" is an
array:
</para>
@ -288,15 +237,15 @@ $collection->save(array("awards" => array("gold", "silver", "bronze")));
<programlisting>
<![CDATA[
{
"_id" : ObjectId("4b06c282edb87a281e09dad9"),
"awards" :
{
"_id" : ObjectId("4b06c282edb87a281e09dad9"),
"awards" :
[
{
"first place" : "gold"
},
{
"second place" : "silver"
"second place" : "silver"
},
{
"third place" : "bronze"
@ -323,7 +272,7 @@ $cursor = $collection->find(array("awards.first place" => "gold"));
<para>
Notice that it doesn't matter that there is a space in the field name
(although it may be best not to use spaces, just to make things more
(although it may be best not to use spaces, just to make things more
readable).
</para>

View file

@ -108,7 +108,7 @@ $db->execute("print('Hello, $username!');");
<?php
$scope = array("user" => $username);
$db->execute(new MongoCode("print('Hello, user!');", $scope));
$db->execute(new MongoCode("print('Hello, '+user+'!');", $scope));
?>
]]>

View file

@ -6,10 +6,10 @@
<section>
<title>Introduction</title>
<para>
This is the 10gen-supported PHP driver for MongoDB.
This is the 10gen-supported PHP driver for MongoDB.
</para>
<para>Here's a quick code sample that connects, inserts documents, queries for
documents, iterates through query results, and disconnects from MongoDB.
documents, iterates through query results, and disconnects from MongoDB.
There are more details on each step in the tutorial below.
</para>
<programlisting role="php">
@ -71,19 +71,19 @@ $connection = new Mongo( "example.com:65432" ); // connect to a remote host at a
]]>
</programlisting>
You do not have to explicitly disconnect from the database. When
<literal>$connection</literal> goes out of scope, the connection will be
You do not have to explicitly disconnect from the database. When
<literal>$connection</literal> goes out of scope, the connection will be
closed automatically and any database resources it was using will be freed.
</para>
<section>
<title>See Also</title>
<para>
The manual chapter on <link linkend="mongo.connecting">connecting</link>
covers different types of connections.
The manual chapter on <link linkend="mongo.connecting">connecting</link>
covers different types of connections.
</para>
<para>
The API documentation on the <classname>Mongo</classname> class and
<function>Mongo::__construct</function> give a comprehensive look at all
The API documentation on the <classname>Mongo</classname> class and
<function>Mongo::__construct</function> give a comprehensive look at all
possible options with a number of examples.
</para>
</section>
@ -103,7 +103,7 @@ $db = $connection->dbname;
]]>
</programlisting>
The database does not need to be created in advance, you can create new
databases by selecting them. Be careful of typos! You can inadvertently
databases by selecting them. Be careful of typos! You can inadvertently
create a new database, which can cause confusing errors:
<programlisting role="php">
@ -122,7 +122,7 @@ $db = $connection->mybiglongdbnme;
<section>
<title>See Also</title>
<para>
The API documentation on the <classname>MongoDB</classname> class contains
The API documentation on the <classname>MongoDB</classname> class contains
more information about database objects.
</para>
</section>
@ -150,7 +150,7 @@ $collection = $connection->baz->foobar;
<section>
<title>See Also</title>
<para>
The API documentation on the <classname>MongoCollection</classname> class
The API documentation on the <classname>MongoCollection</classname> class
contains more information about collection objects.
</para>
</section>
@ -159,7 +159,7 @@ $collection = $connection->baz->foobar;
<section>
<title>Inserting a Document</title>
<para>
Associative arrays are the basic object that can be saved to a collection in
Associative arrays are the basic object that can be saved to a collection in
the database. A somewhat random "document" might be:
<programlisting role="php">
@ -192,10 +192,12 @@ $collection->insert( $doc );
]]>
</programlisting>
</para>
<para>
</para>
<section>
<title>See Also</title>
<para>
The API documentation on <function>MongoCollection::insert</function>
The API documentation on <function>MongoCollection::insert</function>
contains more information about inserting data.
</para>
</section>
@ -206,8 +208,8 @@ $collection->insert( $doc );
Finding Documents using <function>MongoCollection::findOne</function>
</title>
<para>
To show that the document we inserted in the previous step is there, we can
do a simple <function>MongoCollection::findOne</function> operation to get a
To show that the document we inserted in the previous step is there, we can
do a simple <function>MongoCollection::findOne</function> operation to get a
single document from the collection. This method is useful when there only is
one document matching the query or you are only interested in one result.
@ -257,14 +259,14 @@ array(5) {
</programlisting>
</para>
<para>
Note the <literal>_id</literal> field has been added automatically to your
document. <literal>_id</literal> is the "primary key" field that is
Note the <literal>_id</literal> field has been added automatically to your
document. <literal>_id</literal> is the "primary key" field that is
automatically populate for almost all documents in MongoDB.
</para>
<section>
<title>See Also</title>
<para>
The API documentation on <function>MongoCollection::findOne</function>
The API documentation on <function>MongoCollection::findOne</function>
contains more information about finding data.
</para>
</section>
@ -273,7 +275,7 @@ array(5) {
<section>
<title>Adding Multiple Documents</title>
<para>
In order to do more interesting things with queries, let's add multiple
In order to do more interesting things with queries, let's add multiple
simple documents to the collection. These documents will just be
<programlisting role="php">
@ -302,8 +304,8 @@ for($i=0; $i<100; $i++) {
</para>
<para>
Notice that we can insert arrays with different key sets into the same
collection. This aspect is what we mean when we say that MongoDB is
Notice that we can insert arrays with different key sets into the same
collection. This aspect is what we mean when we say that MongoDB is
"schema-free".
</para>
</section>
@ -311,8 +313,8 @@ for($i=0; $i<100; $i++) {
<section>
<title>Counting Documents in A Collection</title>
<para>
Now that we've inserted 101 documents (the 100 we did in the loop, plus the
first one), we can check to see if we have them all using the
Now that we've inserted 101 documents (the 100 we did in the loop, plus the
first one), we can check to see if we have them all using the
<function>MongoCollection::count</function> method.
<programlisting role="php">
<![CDATA[
@ -331,9 +333,9 @@ echo $collection->count();
<title>Using a Cursor to Get All of the Documents</title>
<para>
In order to get all the documents in the collection, we will use
<function>MongoCollection::find</function>. The find() method returns a
<function>MongoCollection::find</function>. The find() method returns a
<classname>MongoCursor</classname> object which allows us to iterate over the
set of documents that matched our query. So to query all of the documents and
set of documents that matched our query. So to query all of the documents and
print them out:
<programlisting role="php">
@ -350,14 +352,14 @@ foreach ($cursor as $id => $value) {
]]>
</programlisting>
and that should print all 101 documents in the collection.
<literal>$id</literal> is the <literal>_id</literal> field of a document,
and that should print all 101 documents in the collection.
<literal>$id</literal> is the <literal>_id</literal> field of a document,
and <literal>$value</literal> is the document itself.
</para>
<section>
<title>See Also</title>
<para>
The API documentation on <function>MongoCollection::find</function>
The API documentation on <function>MongoCollection::find</function>
contains more information about finding data.
</para>
</section>
@ -366,9 +368,9 @@ foreach ($cursor as $id => $value) {
<section>
<title>Setting Criteria for a Query</title>
<para>
We can create a query to pass to the
<function>MongoCollection::find</function> method to get a subset of the
documents in our collection. For example, if we wanted to find the document
We can create a query to pass to the
<function>MongoCollection::find</function> method to get a subset of the
documents in our collection. For example, if we wanted to find the document
for which the value of the "i" field is 71, we would do the following:
<programlisting role="php">
@ -407,7 +409,7 @@ array(2) {
<section>
<title>Getting A Set of Documents With a Query</title>
<para>
We can use the query to get a set of documents from our collection. For
We can use the query to get a set of documents from our collection. For
example, if we wanted to get all documents where "i" &gt; 50, we could write:
<programlisting role="php">
@ -425,7 +427,7 @@ while( $cursor->hasNext() ) {
]]>
</programlisting>
which should print the documents where i &gt; 50. We could also get a range, say
which should print the documents where i &gt; 50. We could also get a range, say
20 &lt; i &lt;= 30:
<programlisting role="php">
@ -443,8 +445,8 @@ while( $cursor->hasNext() ) {
]]>
</programlisting>
As it is easy to forget to escape the "$", you can also choose your own
special character to use instead of '$'. Choose a character that will not
As it is easy to forget to escape the "$", you can also choose your own
special character to use instead of '$'. Choose a character that will not
occur in your key names, e.g. ":", and add the following line to php.ini:
<programlisting>
@ -465,7 +467,7 @@ $query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );
]]>
</programlisting>
You can also change it in your code using ini_set("mongo.cmd", ":"). Of
You can also change it in your code using ini_set("mongo.cmd", ":"). Of
course, you can also just use single quotes around the $.
</para>
</section>
@ -473,8 +475,8 @@ $query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );
<section>
<title>Creating An Index</title>
<para>
MongoDB supports indexes, and they are very easy to add on a collection. To
create an index, you specify the field name and direction: ascending (1) or
MongoDB supports indexes, and they are very easy to add on a collection. To
create an index, you specify the field name and direction: ascending (1) or
descending (-1). The following creates an ascending index on the "i" field:
<programlisting role="php">