我尝试在 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
当然,我还检查了单独运行这些片段以及相同的结果,所以问题是:我在第二种方法中做错了什么?