Class yii\mongodb\Connection

Inheritanceyii\mongodb\Connection » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since 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 \yii\mongodb\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

PropertyTypeDescriptionDefined By
$driverOptions array Options for the MongoDB driver. yii\mongodb\Connection
$dsn string Host:port Correct syntax is: mongodb://[username:password@]host1[:port1][,host2[:port2:],. yii\mongodb\Connection
$enableLogging boolean Whether to log command and query executions. yii\mongodb\Connection
$enableProfiling boolean Whether to enable profiling the commands and queries being executed. yii\mongodb\Connection
$fileStreamProtocol string Name of the protocol, which should be used for the GridFS stream wrapper. yii\mongodb\Connection
$fileStreamWrapperClass string Name of the class, which should serve as a stream wrapper for $fileStreamProtocol protocol. yii\mongodb\Connection
$manager \MongoDB\Driver\Manager MongoDB driver manager. yii\mongodb\Connection
$options array Connection options. yii\mongodb\Connection
$typeMap array Type map to use for BSON unserialization. yii\mongodb\Connection

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
close() Closes the currently active DB connection. yii\mongodb\Connection
createCommand() Creates MongoDB command. yii\mongodb\Connection
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getCollection() Returns the MongoDB collection with the given name. yii\mongodb\Connection
getDatabase() Returns the MongoDB database with the given name. yii\mongodb\Connection
getDefaultDatabaseName() Returns default database name, if it is not set, attempts to determine it from $dsn value. yii\mongodb\Connection
getFileCollection() Returns the MongoDB GridFS collection. yii\mongodb\Connection
getIsActive() Returns a value indicating whether the Mongo connection is established. yii\mongodb\Connection
getLogBuilder() Returns log builder for this connection. yii\mongodb\Connection
getQueryBuilder() Returns the query builder for the this MongoDB connection. yii\mongodb\Connection
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\base\BaseObject
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
open() Establishes a Mongo connection. yii\mongodb\Connection
registerFileStreamWrapper() Registers GridFS stream wrapper for the $fileStreamProtocol protocol. yii\mongodb\Connection
setDefaultDatabaseName() Sets default database name. yii\mongodb\Connection
setLogBuilder() Sets log builder used for this connection. yii\mongodb\Connection
setQueryBuilder() Sets the query builder for the this MongoDB connection. yii\mongodb\Connection
trigger() Triggers an event. yii\base\Component

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
initConnection() Initializes the DB connection. yii\mongodb\Connection
selectDatabase() Selects the database with given name. yii\mongodb\Connection

Events

Hide inherited events

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

Property Details

$driverOptions public property

Options for the MongoDB driver. Any driver-specific options not included in MongoDB connection string specification.

See also http://php.net/manual/en/mongodb-driver-manager.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
$enableLogging public property (available since version 2.1)

Whether to log command and query executions. When enabled this option may reduce performance. MongoDB commands may contain large data, consuming both CPU and memory. It makes sense to disable this option in the production environment.

public boolean $enableLogging true
$enableProfiling public property (available since version 2.1)

Whether to enable profiling the commands and queries being executed. This option will have no effect in case $enableLogging is disabled.

public boolean $enableProfiling true
$fileStreamProtocol public property (available since version 2.1)

Name of the protocol, which should be used for the GridFS stream wrapper. Only alphanumeric values are allowed: do not use any URL special characters, such as '/', '&', ':' etc.

See also yii\mongodb\file\StreamWrapper.

public string $fileStreamProtocol 'gridfs'
$fileStreamWrapperClass public property (available since version 2.1)

Name of the class, which should serve as a stream wrapper for $fileStreamProtocol protocol.

public string $fileStreamWrapperClass 'yii\mongodb\file\StreamWrapper'
$manager public property (available since version 2.1)

MongoDB driver manager.

public \MongoDB\Driver\Manager $manager null
$options public property

Connection options. For example:

[
    'socketTimeoutMS' => 1000, // how long a send or receive on a socket can take before timing out
    'ssl' => true // initiate the connection with TLS/SSL
]

See also https://docs.mongodb.com/manual/reference/connection-string/#connections-connection-options.

public array $options = []
$typeMap public property (available since version 2.1)

Type map to use for BSON unserialization. Note: default type map will be automatically merged into this field, possibly overriding user-defined values.

See also http://php.net/manual/en/mongodb-driver-cursor.settypemap.php.

public array $typeMap = []

Method Details

close() public method

Closes the currently active DB connection.

It does nothing if the connection is already closed.

public void close ( )
createCommand() public method (available since version 2.1)

Creates MongoDB command.

public yii\mongodb\Command createCommand ( $document = [], $databaseName null )
$document array

Command document contents.

$databaseName string|null

Database name, if not set \yii\mongodb\defaultDatabaseName will be used.

return yii\mongodb\Command

Command instance.

getCollection() public method

Returns the MongoDB 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.

getDatabase() public method

Returns the MongoDB database with the given name.

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

Database 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.

getDefaultDatabaseName() public method

Returns default database name, if it is not set, attempts to determine it from $dsn value.

public string getDefaultDatabaseName ( )
return string

Default database name

throws yii\base\InvalidConfigException

if unable to determine default database name.

getFileCollection() public method

Returns the MongoDB 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.

getIsActive() public method

Returns a value indicating whether the Mongo connection is established.

public boolean getIsActive ( )
return boolean

Whether the Mongo connection is established

getLogBuilder() public method (available since version 2.1)

Returns log builder for this connection.

public yii\mongodb\LogBuilder getLogBuilder ( )
return yii\mongodb\LogBuilder

The log builder for this connection.

getQueryBuilder() public method (available since version 2.1)

Returns the query builder for the this MongoDB connection.

public yii\mongodb\QueryBuilder getQueryBuilder ( )
return yii\mongodb\QueryBuilder

The query builder for the this MongoDB connection.

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 ( )
open() public method

Establishes a Mongo connection.

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

public void open ( )
throws yii\mongodb\Exception

if connection fails

registerFileStreamWrapper() public method

Registers GridFS stream wrapper for the $fileStreamProtocol protocol.

public string registerFileStreamWrapper ( $force false )
$force boolean

Whether to enforce registration even wrapper has been already registered.

return string

Registered stream protocol name.

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.

setDefaultDatabaseName() public method

Sets default database name.

public void setDefaultDatabaseName ( $name )
$name string

Default database name.

setLogBuilder() public method (available since version 2.1)

Sets log builder used for this connection.

public void setLogBuilder ( $logBuilder )
$logBuilder array|string|yii\mongodb\LogBuilder

The log builder for this connection.

setQueryBuilder() public method (available since version 2.1)

Sets the query builder for the this MongoDB connection.

public void setQueryBuilder ( $queryBuilder )
$queryBuilder yii\mongodb\QueryBuilder|array|string|null

The query builder for this MongoDB connection.

Event Details

EVENT_AFTER_OPEN event of type \yii\mongodb\Event

An event that is triggered after a DB connection is established