复利 MongoDB 查询
Compound Interest MongoDB Query
正在尝试在我的聚合查询中计算复利。
我创建了这个每周 return 因素数组,并假设起始值为 100 美元
{
"investThis": 100,
"wklyReturns" : [
0.953268776798189,
1.00703473704638,
0.994451681381773,
1.05357596706145,
0.99028490888956,
0.981037037037037,
1.01519025417356,
0.990515443440262,
1.01512249218671,
1.01603072983355,
0.991167064317986,
0.919182492650833,
0.991854491599945,
0.971319397617442,
...
]
}
所有需要做的就是将“investThis”乘以索引 0 return 因子,然后重复使用结果并将其乘以索引 0+1 return 因子,一直到每周回报列表.
这里有一些来自 google sheet 计算的截图...
start drag and drop
final result
非常感谢任何帮助
如果我没理解错的话,你需要做的就是再添加一个聚合步骤:
{
$project: {
"results": {
$reduce: {
input: "$wklyReturns",
initialValue: "$investThis",
in: {
$multiply: [
"$$value",
"$$this"
]
}
}
}
}
}
正如您在 playground 上看到的那样。
$reduce
操作允许您每次使用之前的结果重复一个动作。
正在尝试在我的聚合查询中计算复利。
我创建了这个每周 return 因素数组,并假设起始值为 100 美元
{
"investThis": 100,
"wklyReturns" : [
0.953268776798189,
1.00703473704638,
0.994451681381773,
1.05357596706145,
0.99028490888956,
0.981037037037037,
1.01519025417356,
0.990515443440262,
1.01512249218671,
1.01603072983355,
0.991167064317986,
0.919182492650833,
0.991854491599945,
0.971319397617442,
...
]
}
所有需要做的就是将“investThis”乘以索引 0 return 因子,然后重复使用结果并将其乘以索引 0+1 return 因子,一直到每周回报列表.
这里有一些来自 google sheet 计算的截图...
start drag and drop
final result
非常感谢任何帮助
如果我没理解错的话,你需要做的就是再添加一个聚合步骤:
{
$project: {
"results": {
$reduce: {
input: "$wklyReturns",
initialValue: "$investThis",
in: {
$multiply: [
"$$value",
"$$this"
]
}
}
}
}
}
正如您在 playground 上看到的那样。
$reduce
操作允许您每次使用之前的结果重复一个动作。