Connection works together with Database and 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 Connection::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 Connection::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',
],
],
]
~~~