Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb connect using php

Tags:

php

mongodb

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

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

then it gives error like this

Fatal error: Uncaught exception 'MongoConnectionException' with message 'couldn't get host info for 123@]localhost'

then how to solve this type of problem..

like image 632
Rohan Kumar Avatar asked Jul 06 '12 06:07

Rohan Kumar


2 Answers

Option 1

Pass the credentials via the second argument to the Mongo constructor

$db = new Mongo('mongodb://localhost', array(
    'username' => 'abc',
    'password' => 'abc@123',
    'db'       => 'abc'
));

Option 2

Use the MongoDB::authenticate() method

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

$db->authenticate('abc', 'abc@123');

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' => 'abc@123',
    'db'       => 'abc'
]);
like image 200
Phil Avatar answered Oct 11 '22 02:10

Phil


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";
    }
like image 45
Pransh Tiwari Avatar answered Oct 11 '22 03:10

Pransh Tiwari