sql >> データベース >  >> NoSQL >> MongoDB

Mongodb計算クエリ-累積乗算

    以下の集計を使用できます:

    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)




    1. RubyonRailsアプリからmongodbデータベースとコレクションリストのリストを取得する方法

    2. 範囲クエリのために日付と時刻をMeteorに保存する方法は?

    3. PUGのデータベースからのデータの解析

    4. mongodbドキュメントのすべての配列要素を特定の値に変更するにはどうすればよいですか?