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

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

Aggregation Framework は便利

mongoDBの集計機能、Aggregationフレームワークが便利です。

  • 使用例

テスト用のデータは、"number"というキーに1~10000を順番に入れて作った単純なものです。

> db.testcollection.find()
{ "_id" : ObjectId("519b6ec5fcb9577fd21fcbda"), "number" : 1 }
{ "_id" : ObjectId("519b6ec5fcb9577fd21fcbdb"), "number" : 2 }
{ "_id" : ObjectId("519b6ec5fcb9577fd21fcbdc"), "number" : 3 }
{ "_id" : ObjectId("519b6ec5fcb9577fd21fcbdd"), "number" : 4 }
{ "_id" : ObjectId("519b6ec5fcb9577fd21fcbde"), "number" : 5 }
.
.
.
{ "_id" : ObjectId("519b6ec6fcb9577fd21ff2e9"), "number" : 10000 }

> db.testcollection.count()
10000

# "number" の合計
> db.testcollection.aggregate(
{ $group : { "_id" : null, "total" : { "$sum" : "$number" }} }
)

# 結果
{ "result" : [ { "_id" : null, "total" : 50005000 } ], "ok" : 1 }

# "number" の平均
> db.testcollection.aggregate(
{ $group : { "_id" : null, "average" : { "$avg" : "$number" }} }
)

# 結果
{ "result" : [ { "_id" : null, "average" : 5000.5 } ], "ok" : 1 }

合計:50005000、平均:5000.5 でちゃんとあってます。


$group、$sum、$avg は、Aggregationオペレータと呼ばれるものです。
この他にもいろいろ便利なオペレータがそろってます。
Aggregation Framework Reference — MongoDB Manual 2.4.3