Database Reference
In-Depth Information
The selectCollection() function also lets you select—or switch—collections, as in the following example:
// Connect to the database
$c = new Mongo();
// Selecting the database ('contacts') and collection ('people') you want
// to connect to
$c-> selectDB("contacts")->selectCollection("people");
Before you can select a database or a collection, you sometimes need to find the desired database or collection.
The Mongo class includes two additional commands for listing the available databases, as well as the available
collections. You can acquire a list of available databases by invoking the listDBs() function and printing the output
(which will be placed in an array):
// Connecting to the database
$c = new Mongo();
// Listing the available databases
print_r($c->listDBs());
Likewise, you can use listCollections() to get a list of available collections in a database:
// Connecting to the database
$c = new Mongo();
// Listing the available collections within the 'contacts' database
print_r($c->contacts->listCollections());
the print_r command used in this example is a php command that prints the contents of an array.
the listDBs() function returns an array directly, so the command can be used as a parameter of the print_r function.
Note
The MongoClient class also contains a close() function that you can use to disconnect the PHP session from the
database server. However, using it is generally not required, except in unusual circumstances, because the driver will
automatically close the connection to the database cleanly whenever the Mongo object goes out of scope.
Sometimes you may not want to forcibly close a connection. For example, you may not be sure of the actual state
of the connection, or you may wish to ensure that a new connection can be established. In this case, you can use the
close() function, as shown in the following example:
// Connecting to the database
$c = new Mongo();
// Closing the connection
$c->close();
Inserting Data
So far you've seen how to establish a connection to the database. Now it's time to learn how to insert data into your
collection. The process for doing this is no different in PHP than when using the MongoDB shell. The process has two
steps. First, you define the document in a variable. Second, you insert it using the insert() function.
 
 
Search WWH ::




Custom Search