MongoDB给出奇怪的连接错误

问题描述:

使用PHP连接到MongoDB时遇到问题. 这是我的代码:

I'm having a problem with connecting to MongoDB with PHP. This is my code:

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

这会产生以下错误:

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

发现了问题; 出于某种原因,Mongo仅在127.0.0.1上监听,而不在localhost上监听.

Found the problem; Turns out for some reason Mongo was only listening on 127.0.0.1, not localhost.

因此,使用$server = new Mongo("mongodb://127.0.0.1:27017");而不是$server = new Mongo("mongodb://localhost:27017");解决了问题:)

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

感谢您的帮助, 詹姆斯

Thanks for your help guys, James