PHP code example of pimenvibritania / yii3-mongodb

1. Go to this page and download the library: Download pimenvibritania/yii3-mongodb library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pimenvibritania / yii3-mongodb example snippets




use Pimenvibritania\Yii3Mongodb\Mongo; 
    
return [
   
    // Your code ...
   
    Mongo::class => [
        'class' => Mongo::class,
        '__construct()' => [
            $params['mongodb/mongodb']['uri'],
            $params['mongodb/mongodb']['host'],
            $params['mongodb/mongodb']['username'],
            $params['mongodb/mongodb']['password'],
            $params['mongodb/mongodb']['ssl'],
            $params['mongodb/mongodb']['database'],
            $params['mongodb/mongodb']['retryWrites'],
            $params['mongodb/mongodb']['tlsAllowInvalidCertificates'],
            $params['mongodb/mongodb']['collections'],
        ]
    ],
];



return [
    // Your code ...
    
    "mongodb/mongodb" => [
        "uri" => $_ENV["MONGODB_BASE_URL"],
        "host" => $_ENV["MONGODB_HOST"],
        "username" => $_ENV["MONGODB_USERNAME"],
        "password" => $_ENV["MONGODB_PASSWORD"],
        "database" => $_ENV["MONGODB_DATABASE"],
        "ssl" => "@root/rds-combined-ca-bundle.pem", //SSL configuration path if needed
        "tlsAllowInvalidCertificates" => true,
        "retryWrites" => false,
        "collections" => [
            "yourCollectionAlias" => "yourCollection",
        ],
    ],
];



use Pimenvibritania\Yii3Mongodb\Mongo as MongoClient; 

class Example {
    public function __construct(private MongoClient $mongoClient){}
    
    public function getAll(): array
    {
        return $this->collection()->find(
            [],
            [
                'sort' => [
                    'createdAt' => -1,
                ]
            ]
        )->toArray();
    }
    
    private function collection(): \MongoDB\Collection
    {
        return $this->mongoClient->getCollection("your_collection");
    }
}