Hello, I’m trying to understand how to use mongodb , but get troubles. There are so many different approaches to interact with mongo…
From php manual:
// connect
$connection = new MongoClient();
// select a database
$database = $connection->my_mongo_db;
// select a collection (analogous to a relational database's table)
$collection = $database->customer;
// add a record
$collection->insert([ 'name' => 'John Smith', 'status' => 1]);
In the yii\mongodb\Connection.php source code
$connection = new \yii\mongodb\Connection([
'dsn' => $dsn,
]);
$connection->open();
$database = $connection->getDatabase('my_mongo_db');
$collection = $database->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
//or
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
From examples above I can’t understand additional methods: getDatabase and getCollection. From my mind native methods make the same work and look better. Eg:
//Yii
$database = $connection->getDatabase('my_mongo_db');
$collection = $database->getCollection('customer');
vs
//PHP Mongodb ext
$database = $connection->my_mongo_db;
$collection = $database->customer;
Could I use these approaches (http://php.net/manual/ru/mongo.sqltomongo.php) or I should use the yii\mongodb\Query instead? Or maybe I can mix them?
I want to get work something like this:
$collection = Yii::$app->mongodb->database_name->collection_name;
//or
$connection = Yii::$app->mongodb->open();
$collection = $connection->database_name->collection_name;