我尝试在Mongo DB中设置一些基本灯具。为此,我读取了一组JSON文件,并尝试将它们插入到本地数据库中(我使用管理员权限连接)。这是奇怪的部分。出于某些原因,我写了代码的版本应该基本相同,所以我有一个:
$client = new \MongoClient($connectionURI);
$db = $client->selectDB($database);
$collections = $db->listCollections();
foreach ($collections as $collection) {
//echo "Removing all documents from '$collection'" . PHP_EOL;
$collection->remove();
$tmp = explode('.', (string)$collection);
$collectionName = $tmp[1];
$tmp = explode('_', $tmp[0]);
$dbName = $tmp[1];
$country = $tmp[2];
if(file_exists(__DIR__."/fixtures/{$country}/{$dbName}/{$collectionName}.json")) {
echo "Inserting fixture data into '{$collection}'".PHP_EOL;
$data = json_decode(file_get_contents(__DIR__."/fixtures/{$country}/{$dbName}/{$collectionName}.json"));
$doc = $collection->insert($data, ["w" => "majority"]);
}
}
第二个基于要读取的文件的迭代,而不是列出现有的集合:
$client = new \MongoClient($connectionURI);
foreach(glob(__DIR__.'/fixtures/*', GLOB_ONLYDIR) as $dir) {
$country = basename($dir);
foreach(glob(__DIR__.'/fixtures/'.$country.'/*', GLOB_ONLYDIR) as $dbDir) {
$collections = array_diff(
scandir(__DIR__."/fixtures/{$country}/".basename($dbDir)), ['.', '..']
);
$dbName = 'test_'.basename($dbDir).'_'.$country;
foreach($collections as $collectionFile) {
$collectionName = pathinfo($collectionFile)['filename'];
$data = [];//json_decode(file_get_contents(__DIR__."/fixtures/{$country}/".basenam e($dbDir)."/{$collectionName}.json"));
// $client->$dbName->$collectionName->insert($data);
$db = $client->selectDB($dbName);
$collection = $db->selectCollection($collectionName);
$collection->insert($data, ["w" => "majority"]);
echo $country.'->'.$dbName.'->'.$collectionName.PHP_EOL;
}
}
}
诀窍是第一个实现很好地工作,第二个抛出MongoCursorException
带有身份验证问题。我遇到的问题是两个版本都试图连接到完全相同的数据库和集合。所以我得到以下输出:
Inserting fixture data into 'test_customers_poland.accounts'
PHP Fatal error: Uncaught exception 'MongoCursorException' with message 'Couldn't get connection: Failed to connect to: 127.0.0.1:27017: SASL Authentication failed on database 'test_customers_poland': Authentication failed.' in /srv/dev-api/src/tests/init_databases.php:96
Stack trace:
#0 /srv/dev-api/src/tests/init_databases.php(96): MongoCollection->insert(Array, Array)
#1 {main}
thrown in /s
第96行的rv / dev-api / src / tests / init_databases.php
当然我也检查过单独运行这些片段并得到相同的结果,所以问题是:我在第二种方法中做错了什么?