9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongoDBでドキュメントごとに配列の要素をカウントする (Aggregation Framework)

Last updated at Posted at 2014-11-12

つい忘れてしまうAggregation Frameworkの使い方をメモっておく。

これからやること:
teamsコレクションのドキュメントごとに配列playersの要素をカウントする。

テストデータの準備

テストデータ

{
  "name": "grampus",
  "players": [
    "narazaki",
    "tulio",
    "tamada",
    "taguchi"
  ]
}
{
  "name": "fctokyo",
  "players": [
    "ohta",
    "muto"
  ]
}

テストデータをinsert

> db.teams.insert({ name: "grampus", players: ["narazaki", "tulio", "tamada", "taguchi"] })
> db.teams.insert({ name: "fctokyo", players: ["ohta", "muto"] })

insert後

> db.teams.find()
{ "_id" : ObjectId("54633eb04296e29135e2325d"), "name" : "grampus", "players" : [ "narazaki", "tulio", "tamada", "taguchi" ] }
{ "_id" : ObjectId("54633eb64296e29135e2325e"), "name" : "fctokyo", "players" : [ "ohta", "muto" ] }

Aggregation Frameworkで集計する

> db.teams.aggregate(
  { $project: { players: 1, name: 1 }},
  { $unwind: "$players" },
  { $group: { _id: "$name", count: { $sum: 1 }}}
)
  • $project Aggregationに流す要素の指定
  • $unwind 配列を各要素ごとのドキュメントに展開する
  • $group グループ化
  • $sum はグループ内で $unwind で展開したドキュメントを数えている

集計結果

{ "_id" : "fctokyo", "count" : 2 }
{ "_id" : "grampus", "count" : 4 }

参考にしたページ

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?