2019 Update
I used PHP version 7.0 on Ubuntu 16.04. This is the detailed information to solve the connection problem. (Skip the parts that you have already done) First I manually installed mongodb, and then the mongodb-php driver.
1) Install mongo db. Enter the following commands:
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 $ echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list $ sudo apt-get update $ sudo apt-get install -y mongodb-org
To correctly start Mongdb as a service, that is, automatically start Mongodb at system startup, follow these steps:
Create the mongodb.service file in / etc / systemd / system / by entering the command:
$ sudo nano /etc/systemd/system/mongodb.service
Paste the following contents into it:
[Unit] Description=High-performance, schema-free document-oriented database After=network.target [Service] User=mongodb ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf [Install] WantedBy=multi-user.target
Then enter the following commands:
$ sudo systemctl start mongodb $ sudo systemctl enable mongodb
2) Install mongo-php driver:
$ sudo pecl install mongodb
You may also receive an error message: phpize not found. Phpize is the command that is used to create the build environment. This error may appear during the installation of any pecl extension. To solve this problem, the phpize command was not found, the user must install the php5-dev package. To install it, enter the command:
$ sudo apt-get install php7.0-dev
Then, in the php.ini file, which is located in the /etc/php/7.0/apache2 directory, add the dong mongo extension:
$ sudo nano /etc/php/7.0/apache2/php.ini
Add the following line to the file:
extension = mongodb.so;
(Similarly, you know the exact location of the mongodb.so file is in /usr/lib/php/20151012/mongodb.so.)
Thus, dong mongo is installed along with its driver.
3) Now keep in mind that the mongo-php classes have been changed. Most of the available resources on the network provide solutions using old classes that are being replaced. Below are the links you can link to:
http://php.net/manual/en/set.mongodb.php
http://zetcode.com/db/mongodbphp/
Here are a few commands for basic database operations:
$mng = new MongoDB\Driver\Manager();
To insert data into a database:
$bulk = new MongoDB\Driver\BulkWrite; $doc = ["_id" => new MongoDB\BSON\ObjectID, "data" => $someData, "info" => $someInfo]; $bulk->insert($doc); $mng->executeBulkWrite('dbName.collectionName', $bulk);
To receive data:
$query = new MongoDB\Driver\Query([]); $rows = $mng->executeQuery("dbName.collectionName", $query); foreach ($rows as $row) { echo "$row->data - $row->info\n"; }