スモールデータで使うPowerShellとmongoDB

最近良く耳にするmongoDB。NoSQL、スキーマレスって何? 良くわからないのでちょこっと使ってみることにしました。

デジカメ画像のExifデータをPowerShellで取得してmongoDBに入れる(PowerShell Image Module)スクリプト

# デジカメ画像ファイル格納パス
$pathname = "C:\mongodb\imgs"
# jpegファイル一覧
$files = Get-ChildItem $pathname -Recurse | Where-Object {$_.Extension -eq ".jpg"}
# PowerShell Image Moduleのロード
Import-Module Image
# DB Driverパス指定
$driver_path = "C:\mongodb\driver\CSharpDriver-1.7.0.4714"
Add-Type -Path "$driver_path\MongoDB.Bson.dll"
Add-Type -Path "$driver_path\MongoDB.Driver.dll"

# mongoDB接続
$dbName = "ExifDb"; # DB名
$connectionString = "mongodb://localhost/{0}?safe=true" -f $dbName
$db = [MongoDB.Driver.MongoDatabase]::Create($connectionString)
# collection名
$collectionName = "ExifCollection";
$collection = $db[$collectionName];

foreach( $file in $files ){
	# 画像ファイル情報
	$filefullname = $file.fullname
	$dir_name = Split-Path $filefullname -Parent
	$file_name = Split-Path $filefullname -Leaf
	$file_LastWriteTime = $file.LastWriteTime
	$file_size = $file.Length
	
	# mongoDBに書き込む情報(ファイル情報)※doc.Add 行に " | Out-Null"をつけると速度UPする
	$doc = New-Object MongoDB.Bson.BsonDocument
	$doc.Add("FileFname", [MongoDB.Bson.BsonValue]::Create($file_name))
	$doc.Add("FileDir", [MongoDB.Bson.BsonValue]::Create($dir_name))
	$doc.Add("FileDate", [MongoDB.Bson.BsonValue]::Create($file_LastWriteTime))
	$doc.Add("FileSize", [MongoDB.Bson.BsonValue]::Create($file_size))
	
	# PowerShell Image Module を実行して画像Exif情報を取得する
	$ExifInfo = Get-Exif $filefullname
	$doc.Add("Manufacturer", [MongoDB.Bson.BsonValue]::Create($ExifInfo.Manufacturer))
	$doc.Add("Model", [MongoDB.Bson.BsonValue]::Create($ExifInfo.Model))
	$doc.Add("Width", [MongoDB.Bson.BsonValue]::Create($ExifInfo.Width))
	$doc.Add("Height", [MongoDB.Bson.BsonValue]::Create($ExifInfo.Height))
	$doc.Add("DateTaken", [MongoDB.Bson.BsonValue]::Create($ExifInfo.DateTaken))

	$collection.save($doc)

}