2
2

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のaggregateで積み上げグラフのデータを作る

2
Posted at
{ _id: aaaa, month: 1, count: 10 }
{ _id: bbbb, month: 2, count: 20 }
{ _id: cccc, month: 3, count: 5 }
{ _id: dddd, month: 4, count: 50 }
{ _id: eeee, month: 5, count: 15 }
{ _id: ffff, month: 6, count: 10 }

こんなドキュメントがあったとして、1月からの累積countを各月ごとに出したい場合を想定します。

db.example.aggregate([
  {
    $group: {
      _id: null,
      counts: { $push: { month: "$month", count: "$count" } },
      month: { $push: "$month" }
    }
  },
  {
    $unwind: "$month"
  },
  {
    $project: {
      month: 1,
      count: {
        $reduce: {
          input: "$counts",
          initialValue: 0,
          in: { 
            $add: [
              { $cond: { if : { $gte : [ "$month" ,  "$$this.month" ]},  then :  "$$this.count" ,  else : 0 } },
              "$$value"
            ]
          }
        }
      }
    }
  }
  }])

このクエリを実行すると次のように返ってきます

{ month: 1, count: 10 }
{ month: 2, count: 30 }
{ month: 3, count: 35 }
{ month: 4, count: 85 }
{ month: 5, count: 100 }
{ month: 6, count: 110 }

ポイントは一度$groupで全てをまとめてから、$unwindでバラすことでmonthごとに配列を持ったドキュメントを作成していることです。

aggregateでできることを全て把握してはいないのでもっと上手い方法があればどなたかお教えください。。。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?