Class yii\mongodb\Connection

Inheritanceyii\mongodb\Connection » yii\base\Component
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/Connection.php

Connection represents a connection to a MongoDb server.

Connection works together with yii\mongodb\Database and yii\mongodb\Collection to provide data access to the Mongo database. They are wrappers of the [[MongoDB PHP extension]](http://us1.php.net/manual/en/book.mongo.php).

To establish a DB connection, set $dsn and then call open() to be true.

The following example shows how to create a Connection instance and establish the DB connection:

$connection = new \yii\mongodb\Connection([
    'dsn' => $dsn,
]);
$connection->open();

After the Mongo connection is established, one can access Mongo databases and collections:

$database = $connection->getDatabase('my_mongo_db');
$collection = $database->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);

You can work with several different databases at the same server using this class. However, while it is unlikely your application will actually need it, the Connection class provides ability to use $defaultDatabaseName as well as a shortcut method getCollection() to retrieve a particular collection instance:

// get collection 'customer' from default database:
$collection = $connection->getCollection('customer');
// get collection 'customer' from database 'mydatabase':
$collection = $connection->getCollection(['mydatabase', 'customer']);

Connection is often used as an application component and configured in the application configuration like the following:

[
     'components' => [
         'mongodb' => [
             'class' => '\yii\mongodb\Connection',
             'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
         ],
     ],
]

Public Properties

Hide inherited properties

Property Type Description Defined By
$database yii\mongodb\Database Database instance. yii\mongodb\Connection
$defaultDatabaseName string Name of the Mongo database to use by default. yii\mongodb\Connection
$driverOptions array Options for the MongoDB driver. yii\mongodb\Connection
$dsn string Host:port Correct syntax is: mongodb://[username:password@]host1[:port1][,host2[:port2:],...][/dbname] For example: mongodb://localhost:27017 mongodb://developer:password@localhost:27017 mongodb://developer:password@localhost:27017/mydatabase yii\mongodb\Connection
$fileCollection yii\mongodb\file\Collection Mongo GridFS collection instance. yii\mongodb\Connection
$isActive boolean Whether the Mongo connection is established. yii\mongodb\Connection
$mongoClient \MongoClient Mongo client instance. yii\mongodb\Connection
$options array Connection options. yii\mongodb\Connection

Public Methods

Hide inherited methods

Method Description Defined By
close() Closes the currently active DB connection. yii\mongodb\Connection
getCollection() Returns the Mongo collection with the given name. yii\mongodb\Connection
getDatabase() Returns the Mongo collection with the given name. yii\mongodb\Connection
getFileCollection() Returns the Mongo GridFS collection. yii\mongodb\Connection
getIsActive() Returns a value indicating whether the Mongo connection is established. yii\mongodb\Connection
open() Establishes a Mongo connection. yii\mongodb\Connection

Protected Methods

Hide inherited methods

Method Description Defined By
fetchDefaultDatabaseName() Returns $defaultDatabaseName value, if it is not set, attempts to determine it from $dsn value. yii\mongodb\Connection
initConnection() Initializes the DB connection. yii\mongodb\Connection
selectDatabase() Selects the database with given name. yii\mongodb\Connection

Events

Hide inherited events

Event Type Description Defined By
EVENT_AFTER_OPEN yii\mongodb\Event An event that is triggered after a DB connection is established yii\mongodb\Connection

Property Details

Hide inherited properties

$database public property

Database instance. This property is read-only.

$defaultDatabaseName public property

Name of the Mongo database to use by default. If this field left blank, connection instance will attempt to determine it from $options and $dsn automatically, if needed.

$driverOptions public property

Options for the MongoDB driver.

See also http://www.php.net/manual/en/mongoclient.construct.php.

public array $driverOptions = []
$dsn public property

Host:port

Correct syntax is: mongodb://[username:password@]host1[:port1][,host2[:port2:],...][/dbname] For example: mongodb://localhost:27017 mongodb://developer:password@localhost:27017 mongodb://developer:password@localhost:27017/mydatabase

public string $dsn null
$fileCollection public property

Mongo GridFS collection instance. This property is read-only.

$isActive public property

Whether the Mongo connection is established. This property is read-only.

public boolean $isActive null
$mongoClient public property

Mongo client instance.

public \MongoClient $mongoClient null
$options public property

Connection options. For example:

[
    'socketTimeoutMS' => 1000, // how long a send or receive on a socket can take before timing out
    'journal' => true // block write operations until the journal be flushed the to disk
]

See also http://www.php.net/manual/en/mongoclient.construct.php.

public array $options = []

Method Details

Hide inherited methods

close() public method

Closes the currently active DB connection.

It does nothing if the connection is already closed.

public void close ( )

                public function close()
{
    if ($this->mongoClient !== null) {
        Yii::trace('Closing MongoDB connection: ' . $this->dsn, __METHOD__);
        $this->mongoClient = null;
        $this->_databases = [];
    }
}

            
fetchDefaultDatabaseName() protected method

Returns $defaultDatabaseName value, if it is not set, attempts to determine it from $dsn value.

protected string fetchDefaultDatabaseName ( )
return string

Default database name

throws \yii\base\InvalidConfigException

if unable to determine default database name.

                protected function fetchDefaultDatabaseName()
{
    if ($this->defaultDatabaseName === null) {
        if (isset($this->options['db'])) {
            $this->defaultDatabaseName = $this->options['db'];
        } elseif (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $this->dsn, $matches)) {
            $this->defaultDatabaseName = $matches[1];
        } else {
            throw new InvalidConfigException("Unable to determine default database name from dsn.");
        }
    }
    return $this->defaultDatabaseName;
}

            
getCollection() public method

Returns the Mongo collection with the given name.

public yii\mongodb\Collection getCollection ( $name, $refresh false )
$name string|array

Collection name. If string considered as the name of the collection inside the default database. If array - first element considered as the name of the database, second - as name of collection inside that database

$refresh boolean

Whether to reload the collection instance even if it is found in the cache.

return yii\mongodb\Collection

Mongo collection instance.

                public function getCollection($name, $refresh = false)
{
    if (is_array($name)) {
        list ($dbName, $collectionName) = $name;
        return $this->getDatabase($dbName)->getCollection($collectionName, $refresh);
    } else {
        return $this->getDatabase()->getCollection($name, $refresh);
    }
}

            
getDatabase() public method

Returns the Mongo collection with the given name.

public yii\mongodb\Database getDatabase ( $name null, $refresh false )
$name string|null

Collection name, if null default one will be used.

$refresh boolean

Whether to reestablish the database connection even if it is found in the cache.

return yii\mongodb\Database

Database instance.

                public function getDatabase($name = null, $refresh = false)
{
    if ($name === null) {
        $name = $this->fetchDefaultDatabaseName();
    }
    if ($refresh || !array_key_exists($name, $this->_databases)) {
        $this->_databases[$name] = $this->selectDatabase($name);
    }
    return $this->_databases[$name];
}

            
getFileCollection() public method

Returns the Mongo GridFS collection.

public yii\mongodb\file\Collection getFileCollection ( $prefix 'fs', $refresh false )
$prefix string|array

Collection prefix. If string considered as the prefix of the GridFS collection inside the default database. If array - first element considered as the name of the database, second - as prefix of the GridFS collection inside that database, if no second element present default "fs" prefix will be used.

$refresh boolean

Whether to reload the collection instance even if it is found in the cache.

return yii\mongodb\file\Collection

Mongo GridFS collection instance.

                public function getFileCollection($prefix = 'fs', $refresh = false)
{
    if (is_array($prefix)) {
        list ($dbName, $collectionPrefix) = $prefix;
        if (!isset($collectionPrefix)) {
            $collectionPrefix = 'fs';
        }
        return $this->getDatabase($dbName)->getFileCollection($collectionPrefix, $refresh);
    } else {
        return $this->getDatabase()->getFileCollection($prefix, $refresh);
    }
}

            
getIsActive() public method

Returns a value indicating whether the Mongo connection is established.

public boolean getIsActive ( )
return boolean

Whether the Mongo connection is established

                public function getIsActive()
{
    return is_object($this->mongoClient) && $this->mongoClient->getConnections() != [];
}

            
initConnection() protected method

Initializes the DB connection.

This method is invoked right after the DB connection is established. The default implementation triggers an EVENT_AFTER_OPEN event.

protected void initConnection ( )

                protected function initConnection()
{
    $this->trigger(self::EVENT_AFTER_OPEN);
}

            
open() public method

Establishes a Mongo connection.

It does nothing if a Mongo connection has already been established.

public void open ( )
throws yii\mongodb\Exception

if connection fails

                public function open()
{
    if ($this->mongoClient === null) {
        if (empty($this->dsn)) {
            throw new InvalidConfigException($this->className() . '::dsn cannot be empty.');
        }
        $token = 'Opening MongoDB connection: ' . $this->dsn;
        try {
            Yii::trace($token, __METHOD__);
            Yii::beginProfile($token, __METHOD__);
            $options = $this->options;
            $options['connect'] = true;
            if ($this->defaultDatabaseName !== null) {
                $options['db'] = $this->defaultDatabaseName;
            }
            $this->mongoClient = new \MongoClient($this->dsn, $options, $this->driverOptions);
            $this->initConnection();
            Yii::endProfile($token, __METHOD__);
        } catch (\Exception $e) {
            Yii::endProfile($token, __METHOD__);
            throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
        }
    }
}

            
selectDatabase() protected method

Selects the database with given name.

protected yii\mongodb\Database selectDatabase ( $name )
$name string

Database name.

return yii\mongodb\Database

Database instance.

                protected function selectDatabase($name)
{
    $this->open();
    return Yii::createObject([
        'class' => 'yii\mongodb\Database',
        'mongoDb' => $this->mongoClient->selectDB($name)
    ]);
}

            

Event Details

Hide inherited properties

EVENT_AFTER_OPEN event of type yii\mongodb\Event

An event that is triggered after a DB connection is established