mongDB帳號設定

參考下列指令:

# 環境準備
docker rm -f mongodb_mongo_1
rm -r -f $PWD/db
mkdir -p $PWD/db

# 建立mongoDB
docker run \
  -d \
  --name mongodb_mongo_1 \
  -p 27017:27017 \
  -v $PWD/db:/data/db \
  mongo
sleep 5

# 建立超級管理者
docker exec -it mongodb_mongo_1 bash
mongo admin
db.createUser({ user: "admin" , pwd: "admin1234", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})
quit()
# 重新登入
mongo admin
db.auth("admin","admin1234")
use octblog
db.createUser({
    user: "gevin",
    pwd: "gevin1234",
    roles: [ { role: "readWrite", db: "octblog" },
             { role: "readWrite", db: "octblog-log" } ]
})
quit()

mongo octblog
db.auth("gevin","gevin1234")
use octblog
db.collection.insert({'test':1234});
quit()
exit

# 重啟mongoDB
docker rm -f mongodb_mongo_1
docker run \
  -d \
  --name mongodb_mongo_1 \
  -p 27017:27017 \
  -v $PWD/db:/data/db \
  mongo mongod --auth

MongoDB Replica Set高可用性的建置

  1. 建立三個MongoDB
echo "[info] 建立測試環境";
docker network create mongo-cluster >/dev/null 2>&1
docker rm -f mongo1 mongo2 mongo3 >/dev/null 2>&1
for i in 1 2 3
do
  echo "       mongo${i} 建立"
  docker run \
    -d \
    -p 3000$i:27017 \
    --name mongo$i \
    --net mongo-cluster \
    mongo mongod --replSet my-mongo-set >/dev/null 2>&1
done
  1. 接著設定三者關係,並強制設定electionTimeoutMillis為500ms.
echo "       設定mongo cluster"
docker exec -it mongo3 mongo --eval "config={\"_id\":\"my-mongo-set\",\"members\":[{\"_id\":0,\"host\":\"mongo1:27017\"},{\"_id\":1,\"host\":\"mongo2:27017\"},{\"_id\":2,\"host\":\"mongo3:27017\"}],\"settings\": { \"electionTimeoutMillis\": 500 }}; rs.initiate(config)"
  1. PHP測試
#https://github.com/mongodb/mongo-php-library
require_once __DIR__ . "/vendor/autoload.php";

try{
  $client = new MongoDB\Client("mongodb://mongo1:27017,mongo2:27017,mongo3:27017",[],[
    'typeMap' => [
      'array' => 'array',
      'document' => 'array',
      'root' => 'array',
    ],
  ]);
  $db = $client->selectDatabase('test');
  $cursor = $db->command(['isMaster' => 1]);
  echo "[info] 成功連線至: {$cursor->toArray()[0]['primary']}\n";

} catch(Exception $e) {
  echo "[error] 無法線連\n";
  exit;
}

{  //若Collection:testA不存在則建立.
  if((iterator_count($db->listCollections([
    'filter'=>[
      'name'=>'testA'
    ]
  ])))==0) //當數量為0時,建立testA
    $db->createCollection('testA');
}

//連線至Collection:testA
$collection=$db->selectCollection('testA');

//若沒有任何資料,則建立100則隨機資料
if($collection->count()==0){
  for($i=0;$i<100;$i++){
    $insertOneResult = $collection->insertOne([
      'idx' => $i,
      'value' => "{$i}, rand: ".rand(0,9999),
    ]);
  }
}

//取得最後三筆資料
foreach($collection->find([],[
  'limit' => 3,
  'projection' => ['_id'=>0],
  'sort' => [
    'idx'=>-1
  ]
]) as $rs){
  echo "\tidx:{$rs['idx']}\tvalue:{$rs['value']}\n";
}