I finished the excellent NoSQL Distilled book yesterday and today I tried to start few mongo sessions and configure them as a cluster. This turned out to be a bit tedious, so I wrote a very rough script for it.
It’s two main features are that it spins few instances of mongo and joins them in cluster. And it also wraps the instances in PowerShell process that puts all the output in window title, which enables you to quickly see what runs where and what’s happening.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Add-MongoToPath () { | |
$mongoPath = "C:\Program Files\MongoDB\Server\3.2\bin" | |
if ($env:Path -notlike "*$mongoPath*") | |
{ | |
$env:path += ";$mongoPath" | |
} | |
} | |
function Start-ServerInstace ([string]$ComputerName = "localhost", [int]$Port, [string]$ReplicationSet = "rs0", [string]$DatabasePath) { | |
$process = Start-Process Powershell.exe -PassThru -ArgumentList "-NoProfile", "-Command "" | |
mongod --bind_ip $ComputerName --port $Port --dbpath $DatabasePath --replSet $ReplicationSet | | |
foreach { `$host.ui.rawui.WindowTitle = ""'${ComputerName}:$Port -- ' + `$_""; ""`$_"" | Out-Default } | |
"" " | |
[PsCustomObject]@{ | |
ComputerName = $ComputerName | |
Port=$Port | |
Process = $process | |
} | |
} | |
Add-MongoToPath | |
$script:instances = @() | |
1..10 | foreach { | |
$port = 27000 + $_ | |
$dbPath = "C:\temp\data\db$_" | |
New-Item -ItemType Directory -Force -Path $dbPath | Out-Null | |
$script:instances += Start-ServerInstace -ComputerName localhost -Port $Port -DatabasePath $dbPath -ReplicationSet rs0 | |
Start-Sleep -Seconds 2 | |
if ($_ -eq 1) | |
{ | |
mongo localhost:27001 -eval 'rs.initiate({_id:"rs0", members: [{"_id":1, "host":"localhost:27001"}]})' | |
} | |
else | |
{ | |
mongo localhost:27001 -eval "rs.add('localhost:$port')" | |
} | |
} | |
Start-Process mongo -ArgumentList 'localhost:27001' -Wait | |
#do not use Stop-Process here it does not allow the db to perform it's cleanup | |
$script:instances | foreach { | |
if (-not $_.process.ExitTime) { | |
taskkill /pid $_.process.id | |
} | |
} | |
