PHP insert document mLab

时间:2017-04-10 02:44:44

标签: php mongodb mlab

I'm new at mLab and trying to insert same simple documents to my mongodb on mLab. First of all I was able to insert some documents to the database using the shell (command line) anytime I run the code I get this error:

Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException:
No suitable servers found (`serverSelectionTryOnce` set): [connection timeout calling ismaster on 'ds157390.mlab.com:57390'] in C:\xampp\htdocs\MongoDB\vendor\mongodb\mongodb\src\Collection.php:726 
Stack trace: #0 C:\xampp\htdocs\MongoDB\vendor\mongodb\mongodb\src\Collection.php(726): MongoDB\Driver\Manager->selectServer(Object(MongoDB\Driver\ReadPreference)) 
#1 C:\xampp\htdocs\MongoDB\azureConnect.php(46): MongoDB\Collection->insertMany(Array) #2 {main} thrown in C:\xampp\htdocs\MongoDB\vendor\mongodb\mongodb\src\Collection.php on line 726

PHP-Code:

<?php

ini_set('max_execution_time', 0);

require 'vendor/autoload.php';

$seedData = array(
  array(
    'decade' => '1970s',
    'artist' => 'Debby Boone',
    'song' => 'You Light Up My Life',
    'weeksAtOne' => 10
),
array(
    'decade' => '1980s',
    'artist' => 'Olivia Newton-John',
    'song' => 'Physical',
    'weeksAtOne' => 10
),
array(
    'decade' => '1990s',
    'artist' => 'Mariah Carey',
    'song' => 'One Sweet Day',
    'weeksAtOne' => 16
),
 );

 $uname = "test";
 $pword = "test";
 $uri = "mongodb://".$uname.":".$pword."@ds157390.mlab.com:57390/data4estate";

 $conn = new MongoDB\Client($uri);

 $songs = $conn->data4estate->songs;

 $songs->insertMany($seedData);

1 个答案:

答案 0 :(得分:0)

尝试按照连接时间的说明进行操作:

https://blog.mlab.com/2013/10/do-you-want-a-timeout/

尝试将超时选项设置为连接字符串 https://docs.mongodb.com/manual/reference/connection-string/#uri.connectTimeoutMS

$uri = "mongodb://".$uname.":".$pword."@ds157390.mlab.com:57390/data4estate?connectTimeoutMS=300000";

您可以在php MongoClient上设置socketTimeoutMS,如下所示: PHP MongoDb driver: How to set timeout for executing a code