Core Classes

Table of Contents

The core classes are the most important part of the driver.

The MongoClient class

Introduction

A connection manager for PHP and MongoDB.

This class is used to create and manage connections. A typical use is:

Example #1 MongoClient basic usage

<?php

$m 
= new MongoClient(); // connect
$db $m->foo// get the database named "foo"

?>

See MongoClient::__construct and the section on connecting for more information about creating connections.

Class synopsis

MongoClient
class MongoClient {
/* Constants */
const string MongoClient::VERSION ;
const string MongoClient::DEFAULT_HOST = "localhost" ;
const int MongoClient::DEFAULT_PORT = 27017 ;
const string MongoClient::RP_PRIMARY = "primary" ;
const string MongoClient::RP_PRIMARY_PREFERRED = "primaryPreferred" ;
const string MongoClient::RP_SECONDARY = "secondary" ;
const string MongoClient::RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
const string MongoClient::RP_NEAREST = "nearest" ;
/* Properties */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Methods */
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) ]] )
public bool close ([ boolean|string $connection ] )
public bool connect ( void )
public array dropDB ( mixed $db )
public MongoDB __get ( string $dbname )
public static array getConnections ( void )
public array getHosts ( void )
public array getReadPreference ( void )
public bool killCursor ( string $server_hash , int|MongoInt64 $id )
public array listDBs ( void )
public MongoCollection selectCollection ( string $db , string $collection )
public MongoDB selectDB ( string $name )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public string __toString ( void )
}

Predefined Constants

MongoClient Constants

MongoClient::VERSION
PHP driver version. May be suffixed with "dev", "+" or "-" if it is in-between versions.
MongoClient::DEFAULT_HOST
"localhost"
Host to connect to if no host is given.
MongoClient::DEFAULT_PORT
27017
Port to connect to if no port is given.
MongoClient::RP_PRIMARY
"primary"
Read preference for the primary replica set member.
MongoClient::RP_PRIMARY_PREFERRED
"primaryPreferred"
Read preference for preferring the primary replica set member.
MongoClient::RP_SECONDARY
"secondary"
Read preference for a secondary replica set member.
MongoClient::RP_SECONDARY_PREFERRED
"secondaryPreferred"
Read preference for preferring a secondary replica set member.
MongoClient::RP_NEAREST
"nearest"
Read preference for the nearest replica set member.

Fields

connected
This property will be set to TRUE if we have a open connection the database based on the ReadPreference and tagsets (for ReplicaSet connections), FALSE otherwise. This property does not take authentication into account.
status
This property is no longer used and will be set to NULL In driver versions 1.1.x and earlier, this may be set to a string value (e.g. "recycled", "new") when persistent connections are used.

The MongoDB class

Introduction

Instances of this class are used to interact with a database. To get a database:

Example #1 Selecting a database

<?php

$m 
= new MongoClient(); // connect
$db $m->selectDB("example");

?>
Database names can use almost any character in the ASCII range. However, they cannot contain " ", "." or be the empty string. The name "system" is also reserved.

A few unusual, but valid, database names: "null", "[x,y]", "3", "\"", "/".

Unlike collection names, database names may contain "$".

Class synopsis

MongoDB
class MongoDB {
/* Constants */
const int MongoDB::PROFILING_OFF = 0 ;
const int MongoDB::PROFILING_SLOW = 1 ;
const int MongoDB::PROFILING_ON = 2 ;
/* Fields */
public integer $w = 1 ;
public integer $wtimeout = 10000 ;
/* Methods */
public array authenticate ( string $username , string $password )
public array command ( array $command [, array $options = array() ] )
public __construct ( MongoClient $conn , string $name )
public MongoCollection createCollection ( string $name [, array $options ] )
public array createDBRef ( string $collection , mixed $document_or_id )
public array drop ( void )
public array dropCollection ( mixed $coll )
public array execute ( mixed $code [, array $args = array() ] )
public bool forceError ( void )
public MongoCollection __get ( string $name )
public array getCollectionNames ([ bool $includeSystemCollections = false ] )
public array getDBRef ( array $ref )
public MongoGridFS getGridFS ([ string $prefix = "fs" ] )
public int getProfilingLevel ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array lastError ( void )
public array listCollections ([ bool $includeSystemCollections = false ] )
public array prevError ( void )
public array repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] )
public array resetError ( void )
public MongoCollection selectCollection ( string $name )
public int setProfilingLevel ( int $level )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
public string __toString ( void )
}

Predefined Constants

MongoDB Log Levels

MongoDB::PROFILING_OFF
0
Profiling is off.
MongoDB::PROFILING_SLOW
1
Profiling is on for slow operations (>100 ms).
MongoDB::PROFILING_ON
2
Profiling is on for all operations.

Fields

w
1

The number of servers to replicate a change to before returning success. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

w is used whenever you need to adjust the acknowledgement level (MongoCollection::insert, MongoCollection::update, MongoCollection::remove, MongoCollection::save, and MongoCollection::ensureIndex all support this option). With the default value (1), an acknowledged operation will return once the database server has the operation. If the server goes down before the operation has been replicated to a secondary, it is possible to lose the operation forever. Thus, you can specify w to be higher than one and guarantee that at least one secondary has the operation before it is considered successful.

For example, if w is 2, the primary and one secondary must have a record of the operation or the driver will throw a MongoCursorException. It is tempting to set w to the total number of secondaries + primary, but then if one secondary is down the operation will fail and an exception will be thrown, so usually w=2 is safest (primary and one secondary).

wtimeout
10000

The number of milliseconds to wait for MongoDB::$w replications to take place. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

Unless wtimeout is set, the server waits forever for replicating to w servers to finish. The driver defaults to waiting for 10 seconds, you can change this value to alter its behavior.

See Also

MongoDB core docs on » databases.

The MongoCollection class

Introduction

Represents a MongoDB collection.

Collection names can use any character in the ASCII set. Some valid collection names are "", "...", "my collection", and "*&#@".

User-defined collection names cannot contain the $ symbol. There are certain system collections which use a $ in their names (e.g., local.oplog.$main), but it is a reserved character. If you attempt to create and use a collection with a $ in the name, MongoDB will assert.

Class synopsis

MongoCollection
class MongoCollection {
/* Constants */
const int MongoCollection::ASCENDING = 1 ;
const int MongoCollection::DESCENDING = -1 ;
/* Fields */
public MongoDB $db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* Methods */
public array aggregate ( array $pipeline [, array $op [, array $... ]] )
public mixed batchInsert ( array $a [, array $options = array() ] )
public __construct ( MongoDB $db , string $name )
public int count ([ array $query = array() [, int $limit = 0 [, int $skip = 0 ]]] )
public array createDBRef ( mixed $document_or_id )
public array deleteIndex ( string|array $keys )
public array deleteIndexes ( void )
public array distinct ( string $key [, array $query ] )
public array drop ( void )
public bool ensureIndex ( string|array $key|keys [, array $options = array() ] )
public MongoCursor find ([ array $query = array() [, array $fields = array() ]] )
public array findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] )
public array findOne ([ array $query = array() [, array $fields = array() ]] )
public MongoCollection __get ( string $name )
public array getDBRef ( array $ref )
public array getIndexInfo ( void )
public string getName ( void )
public array getReadPreference ( void )
public bool getSlaveOkay ( void )
public array group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] )
public bool|array insert ( array|object $a [, array $options = array() ] )
public bool|array remove ([ array $criteria = array() [, array $options = array() ]] )
public mixed save ( array|object $a [, array $options = array() ] )
public bool setReadPreference ( string $read_preference [, array $tags ] )
public bool setSlaveOkay ([ bool $ok = true ] )
static protected string toIndexString ( mixed $keys )
public string __toString ( void )
public bool|array update ( array $criteria , array $new_object [, array $options = array() ] )
public array validate ([ bool $scan_data = FALSE ] )
}

Predefined Constants

MongoCollection::ASCENDING
1
Ascending direction for sorts and index creation.
MongoCollection::DESCENDING
-1
Descending direction for sorts and index creation.

Fields

db

The "parent" database for this collection.

w

The number of servers to replicate a change to before returning success. Value is inherited from the parent database. The MongoDB class has a more detailed description of how w works.

wtimeout

The number of milliseconds to wait for $this->w replications to take place. Value is inherited from the parent database. The MongoDB class has a more detailed description of how wtimeout works.

See Also

MongoDB core docs on » collections.

The MongoCursor class

Introduction

A cursor is used to iterate through the results of a database query. For example, to query the database and see all results, you could do:

Example #1 MongoCursor basic usage

<?php

$cursor 
$collection->find();
var_dump(iterator_to_array($cursor));

?>

You don't generally create cursors using the MongoCursor constructor, you get a new cursor by calling MongoCollection::find (as shown above).

Suppose that, in the example above, $collection was a 50GB collection. We certainly wouldn't want to load that into memory all at once, which is what a cursor is for: allowing the client to access the collection in dribs and drabs.

If we have a large result set, we can iterate through it, loading a few megabytes of results into memory at a time. For example, we could do:

Example #2 Iterating over MongoCursor

<?php

$cursor 
$collection->find();

foreach (
$cursor as $doc) {
    
// do something to each document
}

?>
This will go through each document in the collection, loading and garbage collecting documents as needed.

Note that this means that a cursor does not "contain" the database results, it just manages them. Thus, if you print a cursor (with, say, var_dump or print_r), you'll just get the cursor object, not your documents. To get the documents themselves, you can use one of the methods shown above.

Cursor Stages

A MongoCursor has two "life stages": pre- and post- query. When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including adding limits, skips, sorts, and more advanced options.

When the client attempts to get a result (by calling MongoCursor::next, directly or indirectly), the cursor moves into the post-query stage. At this point, the query has been executed by the database and cannot be modified anymore.

Example #3 Adding options to MongoCursor

<?php

$cursor 
$collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>

Class synopsis

MongoCursor
class MongoCursor implements Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 30000 ;
/* Methods */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor awaitData ([ bool $wait = true ] )
public MongoCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ bool $foundOnly = FALSE ] )
public array current ( void )
public bool dead ( void )
protected void doQuery ( void )
public array explain ( void )
public MongoCursor fields ( array $f )
public array getNext ( void )
public array getReadPreference ( void )
public bool hasNext ( void )
public MongoCursor hint ( mixed $index )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string key ( void )
public MongoCursor limit ( int $num )
public void next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor setFlag ( int $flag [, bool $set = true ] )
public MongoCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ bool $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ bool $tail = true ] )
public MongoCursor timeout ( int $ms )
public bool valid ( void )
}

Static Variables

slaveOkay

If the query should have the "slaveOkay" flag set, which allows reads on the secondary (secondaries are, by default, just for backup and not queried). Can be overridden with MongoCursor::slaveOkay.

This functionality is deprecated. Please use Read Preferences instead.

timeout

Set timeout in milliseconds for all database responses. Use -1 to wait forever. Can be overridden with MongoCursor::timeout. This does not cause the MongoDB server to cancel the operation; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time.

See Also

MongoDB core docs on » cursors.