MongoDB gives a strange connection error

I have a problem connecting to MongoDB with PHP. This is my code:

<?php
$server = new Mongo('localhost:27017'); 
$db = $server->sampleDB;
$coll = $db->sample;
?>

This results in the following error:

Fatal error: Uncaught exception 'MongoConnectionException' with message 'localhost:27017: couldn't get host info for localhost' in /var/www/example/index.php:2 Stack trace: #0 /var/www/example/index.php(2): Mongo->__construct('localhost:27017') #1 {main} thrown in /var/www/wexample/index.php on line 2
+5
source share
2 answers

Found a problem; Apparently, Mongo listened only 127.0.0.1, not localhost.

So using $server = new Mongo("mongodb://127.0.0.1:27017");instead $server = new Mongo("mongodb://localhost:27017");fixed the problem :)

Thanks for the help guys James

+5
source

Following PHP Guide

Failed to get host information for [server]

This indicates that DNS cannot resolve the address of the server you specified. This can easily be caused by a typo, for example, “server” instead of “$ Server”.

, MongoDB PHP doc

?:

$server = new Mongo("mongodb://localhost:27017");
+2

All Articles