Home » Php » mongodb connect using php

mongodb connect using php

Posted by: admin July 12, 2020 Leave a comment

Questions:

What if password having @ in mongodb connect
mongodb://[username:[email protected]]host1[:port1][,host2[:port2:],…]/db
suppose username='abc' and password='[email protected]'
and in php we create mongo db instance like

$m = new Mongo('mongodb://[abc:[email protected]@]localhost/abc');

then it gives error like this

Fatal error: Uncaught exception ‘MongoConnectionException’ with message ‘couldn’t get host info for [email protected]]localhost’

then how to solve this type of problem..

How to&Answers:

Option 1

Pass the credentials via the second argument to the Mongo constructor

$db = new Mongo('mongodb://localhost', array(
    'username' => 'abc',
    'password' => '[email protected]',
    'db'       => 'abc'
));

Option 2

Use the MongoDB::authenticate() method

$m = new Mongo();
$db = $m->abc;

$db->authenticate('abc', '[email protected]');

Keep in mind…

There is a major disadvantage to this method: if the connection is dropped and then reconnects, the new connection will not be authenticated. If you use the URI format, the PHP driver will automatically authenticate the user whenever a new connection is made.

2014 Update

Instanciating Mongo directly is now deprecated. The advice is to use MongoClient instead with the same arguments as above. For example

$m = new MongoClient('mongodb://localhost', [
    'username' => 'abc',
    'password' => '[email protected]',
    'db'       => 'abc'
]);

Answer:

2019 Update

I have used php version 7.0 on ubuntu 16.04. This is a detailed info for solving the connectivity issue. (Skip the parts which you have already done)
First I manually installed mongodb and then the mongodb-php driver for it.

1) Installing 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

In order to properly launch Mongdb as a service, ie automatically starting Mongodb when the system starts, follow the following steps:

Create file mongodb.service in /etc/systemd/system/ by entering the command:

$ sudo nano /etc/systemd/system/mongodb.service

Paste the following contents in 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) Installing the mongo-php driver:

$ sudo pecl install mongodb

Also you might receive error: phpize not found. Phpize is a command which is used to create a build environment. This error could appear at the time of installation of any pecl extension. To solve this problem of the phpize command not found, the user has to 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 in /etc/php/7.0/apache2 directory, add the mongo db extension:

$ sudo nano /etc/php/7.0/apache2/php.ini 

Add the following line in the file:

extension = mongodb.so;

(Just so you know, the exact location of the file mongodb.so is in /usr/lib/php/20151012/mongodb.so.)

So the mongo db is installed along with its driver.

3) Now keep in mind that the mongo-php classes have been changed. Most of the available resources in the net give solutions using old classes which is superseded. Below are the links which you can refer to:

http://php.net/manual/en/set.mongodb.php

http://zetcode.com/db/mongodbphp/

Here are some commands for basic database operations:

$mng = new MongoDB\Driver\Manager(); // Driver Object created

To insert data into the database:

$bulk = new MongoDB\Driver\BulkWrite;

$doc = ["_id" => new MongoDB\BSON\ObjectID, "data" => $someData, "info" => $someInfo];

$bulk->insert($doc);

$mng->executeBulkWrite('dbName.collectionName', $bulk);

For fetching data:

$query = new MongoDB\Driver\Query([]); 

$rows = $mng->executeQuery("dbName.collectionName", $query);

foreach ($rows as $row) 
    {
         echo "$row->data - $row->info\n";
    }

Answer:

Using new Mongo(); can create problems

“Warning: Instanciating this class will emit E_DEPRECATED warning, and turn off acknowledged writes.” – php.com

Use MongoClient() insted

$m = new MongoClient("mongodb://testUser:[email protected]:myportnumber");