以下の集計を使用できます:
db.ccpsample.aggregate([
{ $sort: { ccp_id: 1, period: 1 } },
{
$group: {
_id: "$ccp_id",
items: { $push: "$$ROOT" },
baseSale: { $first: "$sales" },
growths: { $push: "$growth" }
}
},
{
$unwind: {
path: "$items",
includeArrayIndex: "index"
}
},
{
$project: {
cpp_id: "$items.cpp_id",
period: "$items.period",
growth: "$items.growth",
sales: {
$cond: {
if: { $ne: [ "$items.sales", "NULL" ] },
then: "$items.sales",
else: {
$reduce: {
input: { $slice: [ "$growths", "$index" ] },
initialValue: "$baseSale",
in: { $multiply: [ "$$value", { $add: [1, { $divide: [ "$$this", 100 ] }] } ] }
}
}
}
}
}
}
])
基本的に、n-th
の値を計算します 次のことを知っておく必要がある要素:
- 最初の要素の販売額(
$first
$group
内 ) - すべての
growths
の配列 ($push
$group
内 ) -
n
これは、実行する必要のある乗算の数を示します
インデックスを計算するには、$push
を実行する必要があります すべての要素を1つの配列にまとめてから、 $unwind
includeArrayIndex
を使用 巻き戻された配列のインデックスをフィールドindex
に挿入するオプション 。
最後のステップでは、累積乗算を計算します。 $slice
を使用します index
を使用 growths
の数を評価するフィールド 処理する必要があります。したがって、601
には1つの要素があります 、602
の2つの要素 など。
次に、 $reduce
の時間です。 その配列を処理し、数式に基づいて乗算を実行するには:(1 + (growth/100)
)