PowerShellからmongoDBのAggregationを実行する(パイロット版)
mongoDBクライアントからの実行が便利なのでわざわざPowerShellから実行する必要もないのですが、他にやっている人もいないようなので試行錯誤の結果を公開してみます。使用するデータは前回と同じものです。
要は、mongoDBクライアントで使用したパラメータをBSON型にしてaggregateに渡せば良いみたいですが、変換の仕方がよくわからず苦労しました。オペレータの"$"をエスケープしたりしてようやく動くようになりました。
きっともっとスマートな方法があるはずなので、ひとまずパイロット版(とりあえず動きます版)として公開します。
# mongoDB定義 $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"; $dbName = "TestDB" $connectionString = "mongodb://localhost/{0}?safe=true" -f $dbName $db = [MongoDB.Driver.MongoDatabase]::Create($connectionString) # collection名 $collectionName = "testcollection"; $collection = $db[$collectionName]; # "number" の合計 #db.testcollection.aggregate( # { $group : { "_id" : null, "total" : { "$sum" : "$number" }} } #) [MongoDB.Bson.BsonDocument] $doc_total = @{ '$group' = [MongoDB.Bson.BsonDocument] @{ "_id" = 'null'; "total" = [MongoDB.Bson.BsonDocument] @{ "`$sum" = "`$number"}} } # aggregation 合計 $pipeline = $doc_total $collection.aggregate($pipeline).ResultDocuments # "number" の平均 #db.testcollection.aggregate( # { $group : { "_id" : null, "average" : { "$avg" : "$number" }} } #) [MongoDB.Bson.BsonDocument] $doc_average = @{ '$group' = [MongoDB.Bson.BsonDocument] @{ "_id" = 'null'; "total" = [MongoDB.Bson.BsonDocument] @{ "`$avg" = "`$number"}} } # aggregation 平均 $pipeline = $doc_average $collection.aggregate($pipeline).ResultDocuments
<実行結果>
Name Value ---- ----- _id null total 50005000 _id null total 5000.5