Connecting
- Connecting to MongoDB can be as easy as new Mongo, but
- there are many additional options and configurations. The
+ Connecting to MongoDB can be as easy as new Mongo, but
+ there are many additional options and configurations. The
Mongo::__construct page covers all of the API options,
but this page gives some more details and advice for practical use cases.
@@ -14,9 +14,27 @@
Logging In on Connection
- If MongoDB is started with the --auth option, connections
- must be authenticated before they are used. You can do this on a
- per-database level with MongoDB::authenticate:
+ If MongoDB is started with the --auth or
+ --keyFile 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:
+
+
+
+]]>
+
+
+ If your connection is dropped, the driver will automatically attempt to
+ reconnect and reauthenticate you.
+
+
+ You can also authenticate on a per-database level with
+ MongoDB::authenticate:
authenticate($username, $password);
dropped and then reconnected, the connection will no longer be authenticated.
- If you use the connection string format described by
- Mongo::__construct, the database will authenticate on
- connection and reauthenticate if the connection is re-established.
-
-
- This is equivalent to the code above, except that reconnections to the
- database will be authenticated automatically:
-
-
-
-]]>
-
-
- 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:
true));
+$m = new Mongo("mongodb://localhost:27017", array("replicaSet" => "myReplSetName"));
?>
]]>
- 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).
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
MongoConnectionException will be thrown.
- 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.
- 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.
- For more information on replica sets, see the
+ For more information on replica sets, see the
core documentation.
-
- Persistent Connections
-
-
- 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.
-
-
-
- For example, this simple program connects to the database 1000 times:
-
-
-
-
-]]>
-
-
-
- It takes approximately 18 seconds to execute. If we change it to use a
- persistent connection:
-
-
-
- "x"));
-}
-
-?>
-]]>
-
-
-
- ...it takes less than .02 seconds to execute, as it only makes one database
- connection.
-
-
-
- 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.
-
-
- Persistent connections are highly recommended 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.
-
-
- Persistent connections will become the default connection type in 1.0.12. To
- create a non-persistent connection, you will need to pass
- "persist" => false to
- Mongo::__construct.
-
-
-
Domain Socket Support
- 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-<port>.sock.
- 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:
@@ -224,4 +156,93 @@ $m = new Mongo("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");
+
+ Connection Pooling
+
+ In version 1.2.0+, the driver will automatically manage connection pools for
+ the user.
+
+
+ When a user creates a new instance of Mongo, all
+ necessary connections will be taken from their pools (replica set connections
+ may require multple connections). When the Mongo
+ instance goes out of scope, the connections will be returned to the pool.
+
+
+
+
+ Persistent Connections
+
+
+ This section is not relevant for 1.2.0+. In 1.2.0+, connections are always
+ persistent and managed automatically by the driver.
+
+
+
+
+ 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.
+
+
+
+ For example, this simple program connects to the database 1000 times:
+
+
+
+
+]]>
+
+
+
+ It takes approximately 18 seconds to execute. If we change it to use a
+ persistent connection:
+
+
+
+ "x"));
+}
+
+?>
+]]>
+
+
+
+ ...it takes less than .02 seconds to execute, as it only makes one database
+ connection.
+
+
+
+ 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.
+
+
+ Persistent connections are highly recommended 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.
+
+
+ Persistent connections will become the default connection type in 1.0.12. To
+ create a non-persistent connection, you will need to pass
+ "persist" => false to
+ Mongo::__construct.
+
+
+
diff --git a/reference/mongo/mongo/gethosts.xml b/reference/mongo/mongo/gethosts.xml
index 343a1e2d60..c324672de9 100644
--- a/reference/mongo/mongo/gethosts.xml
+++ b/reference/mongo/mongo/gethosts.xml
@@ -15,13 +15,8 @@
- 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).
-
-
-
- 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.
@@ -39,98 +34,54 @@
&reftitle.returnvalues;
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:
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)
+ }
+}
]]>
- 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.
@@ -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
--->
+-->
diff --git a/reference/mongo/mongo/getpoolsize.xml b/reference/mongo/mongo/getpoolsize.xml
new file mode 100644
index 0000000000..44ddd4d610
--- /dev/null
+++ b/reference/mongo/mongo/getpoolsize.xml
@@ -0,0 +1,48 @@
+
+
+
+
+
+ Mongo::getPoolSize
+ Get pool size for connection pools
+
+
+
+ &reftitle.description;
+
+ publicintMongo::getPoolSize
+
+
+
+
+
+ &reftitle.parameters;
+ &no.function.parameters;
+
+
+
+ &reftitle.returnvalues;
+
+ Returns the current pool size.
+
+
+
+
diff --git a/reference/mongo/mongo/pooldebug.xml b/reference/mongo/mongo/pooldebug.xml
new file mode 100644
index 0000000000..1bf6cb7303
--- /dev/null
+++ b/reference/mongo/mongo/pooldebug.xml
@@ -0,0 +1,111 @@
+
+
+
+
+
+ Mongo::poolDebug
+ Returns information about all connection pools.
+
+
+
+ &reftitle.description;
+
+ publicarrayMongo::poolDebug
+
+
+
+
+ Returns an array of information about all connection pools.
+
+
+
+
+ &reftitle.parameters;
+ &no.function.parameters;
+
+
+
+ &reftitle.returnvalues;
+
+ Each connection pool has an identifier, which starts with the host. For each
+ pool, this function shows the following fields:
+
+
+
+ in use
+
+
+
+ The number of connections currently being used by
+ Mongo instances.
+
+
+
+
+
+ in pool
+
+
+
+ The number of connections currently in the pool (not being used).
+
+
+
+
+
+ remaining
+
+
+
+ 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
+ Mongo before we exhausted this pool (assuming no
+ instances of Mongo went out of scope, returning
+ their connections to the pool).
+
+
+ A negative number means that this pool will spawn unlimited connections.
+
+
+ Before a pool is created, you can change the max number of connections by
+ calling Mongo::setPoolSize. Once a pool is showing
+ up in the output of this function, its size cannot be changed.
+
+
+
+
+
+ timeout
+
+
+
+ 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.
+
+
+
+
+
+
+
+
diff --git a/reference/mongo/mongo/setpoolsize.xml b/reference/mongo/mongo/setpoolsize.xml
new file mode 100644
index 0000000000..e368e2f561
--- /dev/null
+++ b/reference/mongo/mongo/setpoolsize.xml
@@ -0,0 +1,67 @@
+
+
+
+
+
+ Mongo::setPoolSize
+ Set the size for future connection pools.
+
+
+
+ &reftitle.description;
+
+ publicboolMongo::setPoolSize
+ intsize
+
+
+
+ Sets the max number of connections new pools will be able to create.
+
+
+
+
+ &reftitle.parameters;
+
+
+
+
+ size
+
+
+
+ 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.
+
+
+
+
+
+
+
+
+ &reftitle.returnvalues;
+
+ Returns the former value of pool size.
+
+
+
+
diff --git a/reference/mongo/queries.xml b/reference/mongo/queries.xml
index f28109dfa3..018c3f4cce 100644
--- a/reference/mongo/queries.xml
+++ b/reference/mongo/queries.xml
@@ -11,7 +11,7 @@
If you are using a
replica set 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
cannot be used with "normal" master-slave.
@@ -20,10 +20,10 @@
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":
connection,
- database,
- collection, and
+ database,
+ collection, and
cursor. Each class inherits the
"slaveOkay" setting from the class above it, so if you do:
@@ -43,7 +43,7 @@ $cursor = $c->find();
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).
@@ -51,21 +51,23 @@ $cursor = $c->find();
How slaves are chosen
- Each instance of Mongo 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 Mongo 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:
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:
-m1's slave is: ip2
-m2's slave is: ip1
+m1's slave is: australianHost
+m2's slave is: europeanHost
-
- If we continued to create new Mongos, we should get a
- fairly even distribution between ip1 and ip2. Keep in mind that all
- secondaries listed by the isMaster 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.
-
-
-
- Slaves are chosen on a per-instance basis and do no change (unless something
- bad happens to your set and they are forced to).
-
-
You can see what the driver thinks is the current status of the set members
by running Mongo::getHosts.
- 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 Mongo::getHosts (some fields omitted for
- clarity):
-
-
- 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
- )
-
-)
-]]>
-
-
- 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 Mongo::getHosts.
- If you enjoy twiddling knobs that you probably shouldn't mess with, you can
- force the driver to use a different slave by calling
- Mongo::switchSlave. 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
+ Mongo::switchSlave. This may choose a new slave
+ (if one is available) and shouldn't be used unless you know what you're
+ doing.
@@ -156,19 +106,18 @@ Array
Random notes
- 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.
- 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 Mongo::getHosts.
+ 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.
-
+
- 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).
@@ -202,10 +151,10 @@ $joe = $people->findOne(array("_id" => $person['_id']));
- Unless the user has specified otherwise, the _id field is a
- MongoId. The most common mistake is attepting to use
- a string to match a MongoId. 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
+ MongoId. The most common mistake is attepting to use
+ a string to match a MongoId. 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:
@@ -232,11 +181,11 @@ $joe = $people->findOne(array("_id" => $pid));
Arrays
- 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.
@@ -255,8 +204,8 @@ $collection->save(array("awards" => array("gold", "silver", "bronze")));
- 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:
@@ -265,9 +214,9 @@ $collection->save(array("awards" => array("gold", "silver", "bronze")));
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}
]]>
-
+
- 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:
@@ -288,15 +237,15 @@ $collection->save(array("awards" => array("gold", "silver", "bronze")));
find(array("awards.first place" => "gold"));
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).
diff --git a/reference/mongo/security.xml b/reference/mongo/security.xml
index 34d3f604f5..77bd5373e2 100644
--- a/reference/mongo/security.xml
+++ b/reference/mongo/security.xml
@@ -108,7 +108,7 @@ $db->execute("print('Hello, $username!');");
$username);
-$db->execute(new MongoCode("print('Hello, user!');", $scope));
+$db->execute(new MongoCode("print('Hello, '+user+'!');", $scope));
?>
]]>
diff --git a/reference/mongo/tutorial.xml b/reference/mongo/tutorial.xml
index 1268a55595..b506f145af 100644
--- a/reference/mongo/tutorial.xml
+++ b/reference/mongo/tutorial.xml
@@ -6,10 +6,10 @@
Introduction
- This is the 10gen-supported PHP driver for MongoDB.
+ This is the 10gen-supported PHP driver for MongoDB.
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.
@@ -71,19 +71,19 @@ $connection = new Mongo( "example.com:65432" ); // connect to a remote host at a
]]>
- You do not have to explicitly disconnect from the database. When
- $connection goes out of scope, the connection will be
+ You do not have to explicitly disconnect from the database. When
+ $connection goes out of scope, the connection will be
closed automatically and any database resources it was using will be freed.
See Also
- The manual chapter on connecting
- covers different types of connections.
+ The manual chapter on connecting
+ covers different types of connections.
- The API documentation on the Mongo class and
- Mongo::__construct give a comprehensive look at all
+ The API documentation on the Mongo class and
+ Mongo::__construct give a comprehensive look at all
possible options with a number of examples.
@@ -103,7 +103,7 @@ $db = $connection->dbname;
]]>
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:
@@ -122,7 +122,7 @@ $db = $connection->mybiglongdbnme;
See Also
- The API documentation on the MongoDB class contains
+ The API documentation on the MongoDB class contains
more information about database objects.
@@ -150,7 +150,7 @@ $collection = $connection->baz->foobar;
See Also
- The API documentation on the MongoCollection class
+ The API documentation on the MongoCollection class
contains more information about collection objects.
@@ -159,7 +159,7 @@ $collection = $connection->baz->foobar;
Inserting a Document
- 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:
@@ -192,10 +192,12 @@ $collection->insert( $doc );
]]>
+
+ See Also
- The API documentation on MongoCollection::insert
+ The API documentation on MongoCollection::insert
contains more information about inserting data.
@@ -206,8 +208,8 @@ $collection->insert( $doc );
Finding Documents using MongoCollection::findOne
- To show that the document we inserted in the previous step is there, we can
- do a simple MongoCollection::findOne operation to get a
+ To show that the document we inserted in the previous step is there, we can
+ do a simple MongoCollection::findOne 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) {
- Note the _id field has been added automatically to your
- document. _id is the "primary key" field that is
+ Note the _id field has been added automatically to your
+ document. _id is the "primary key" field that is
automatically populate for almost all documents in MongoDB.
See Also
- The API documentation on MongoCollection::findOne
+ The API documentation on MongoCollection::findOne
contains more information about finding data.
@@ -273,7 +275,7 @@ array(5) {
Adding Multiple Documents
- 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
@@ -302,8 +304,8 @@ for($i=0; $i<100; $i++) {
- 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".
@@ -311,8 +313,8 @@ for($i=0; $i<100; $i++) {
Counting Documents in A Collection
- 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
MongoCollection::count method.
count();
Using a Cursor to Get All of the Documents
In order to get all the documents in the collection, we will use
- MongoCollection::find. The find() method returns a
+ MongoCollection::find. The find() method returns a
MongoCursor 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:
@@ -350,14 +352,14 @@ foreach ($cursor as $id => $value) {
]]>
- and that should print all 101 documents in the collection.
- $id is the _id field of a document,
+ and that should print all 101 documents in the collection.
+ $id is the _id field of a document,
and $value is the document itself.
See Also
- The API documentation on MongoCollection::find
+ The API documentation on MongoCollection::find
contains more information about finding data.
@@ -366,9 +368,9 @@ foreach ($cursor as $id => $value) {
Setting Criteria for a Query
- We can create a query to pass to the
- MongoCollection::find 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
+ MongoCollection::find 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:
@@ -407,7 +409,7 @@ array(2) {
Getting A Set of Documents With a Query
- 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" > 50, we could write:
@@ -425,7 +427,7 @@ while( $cursor->hasNext() ) {
]]>
- which should print the documents where i > 50. We could also get a range, say
+ which should print the documents where i > 50. We could also get a range, say
20 < i <= 30:
@@ -443,8 +445,8 @@ while( $cursor->hasNext() ) {
]]>
- 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:
@@ -465,7 +467,7 @@ $query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );
]]>
- 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 $.
@@ -473,8 +475,8 @@ $query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );
Creating An Index
- 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: