mongodb connect using php
mongodb, php
Solution
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'
]);
Problem
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..