{ _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でできることを全て把握してはいないのでもっと上手い方法があればどなたかお教えください。。。