We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to configure MongoDB in Phalcon 3 ?

I can't seem to configure MongoDB properly in Phalcon; Software used; PHP 7.1.5 / Phalcon 3.1.2 / MongoDB 3.4.3

Here is what I've tried so far;

    use Phalcon\Mvc\Collection\Manager;
    use Phalcon\Db\Adapter\Mongo\Client;

    $ld->registerNamespaces([
        'Phalcon' => '../Library/Phalcon/',
    ])->register();

    $di->setShared('mongo', function() {
        $mongo = new Client('mongodb:://127.0.0.1:27017');
        return $mongo->selectDb('test');
    }); #mongo

    $di->setShared('collectionManager', function () {
        return new Manager();
    }); #manager

What am I doing wrong here ? In my php error log, I see this; PHP Fatal error: Class 'MongoClient' not found

Thank You!

if(!extension_loaded("mongo")) throw new \Exception("Mongo DB extension is not installed for PHP");

You need MongoDB driver (legacy) named mongo. The best would be to use current, supported driver: https://php.net/manual/en/set.mongodb.php

edited May '17

@Lajos Bencz, Yes "mongo" is not installed, "mongodb" is how can I use it with PHP7 + Phalcon3 ?

@Jonathan Aaron Steel, I've tried installing it with "sudo pecl install mongodb", but I'm still unable to use "mongodb" in Phalcon.

There is just no good setup/config examples in Phalcon documentation to use MongoDB properly. O_O

I got it working now, I was missing getSource function.

public function getSource() {
   return 'table';
}

But is there a way to use MongoDB in Phalcon without having to use Incubator Adapter?

Also, I was able to use "find()" "findFirst()" "save()" but how do you use "DELETE" one or multiple rows ? Thanks.



93

Man, I'm stuck on this... Is there something else that you executed to make it work?!



93
edited Jun '18

Now it's working:

I changed from this

$di->setShared('mongo', function() {
    $mongo = new Client('mongodb:://127.0.0.1:27017');
    return $mongo->selectDb('database');
});

To this:

$di->set('mongo', function () {
    $mongo = new Phalcon\Db\Adapter\MongoDB\Client("mongodb://localhost:27017");
    return $mongo->selectDatabase('database');
}, true);