Search code examples
phpmongodbsymfonysymfony4

Use MongoDB with Symfony 4


I've a some little problems with Symfony 4 and MongoDB Atlas (cloud cluster... but in local i think it's the same). I'm on Windows 10 pro with php 7.1.1.

Based on this article

http://php.net/manual/en/mongodb.tutorial.library.php

this is the code inside my admin controller

 $mongo = new MongoClient();
        $dbs = $mongo->listDBs();
        print_r($dbs);

i receive this error

Attempted to load class "MongoClient" from namespace "App\Controller\Admin".
Did you forget a "use" statement for "MongoClient"?

but: my extension is loaded correctly.

MongoDb ext. phpinfo() output

mongodb
MongoDB support enabled
MongoDB extension version   1.3.4
MongoDB extension stability     stable
libbson bundled version     1.8.2
libmongoc bundled version   1.8.2
libmongoc SSL   enabled
libmongoc SSL library   OpenSSL
libmongoc crypto    enabled
libmongoc crypto library    libcrypto
libmongoc crypto system profile     disabled
libmongoc SASL  enabled
Directive   Local Value Master Value
mongodb.debug   no value

composer.json

"alcaeus/mongo-php-adapter": "^1.1",
"doctrine/mongodb": "^1.6",
"doctrine/mongodb-odm": "^1.2",
"doctrine/mongodb-odm-bundle": "^3.4",
"mongodb/mongodb": "^1.2",

Composer Version

1.6

I also use mongodb-odm-bundle. This work fine, but i'd like to use also official legacy mongodb lib in my projects (connection with cluster it's ok). But when i try to use MongoClient() i get this error...

so, which "use statement" i must to use?


Solution

  • The correct configuration for Symfony 4 + Mongodb Atlas

    1) composer require mongodb/mongodb (nothing else)

    CONTROLLER

    namespace App\Controller\your_controller;
    

    INCLUDE LIBRARY

    use MongoDB;
    

    CONNECTION (for example get the databases list)

    $connection = 'mongodb://___full_URI_MongoDBAtlas___';
    $client = new MongoDB\Client($connection);
    $dbs = $client->listDatabases();
    var_dump($dbs);