Tha*_*ddy 6 mongodb calculation
我最近开始在Mongodb工作POC.我下面有一个json系列
db.ccpsample.insertMany([
{
"ccp_id":1,
"period":601,
"sales":100.00
},
{
"ccp_id":1,
"period":602,
"growth":2.0,
"sales":"NULL" ##sales=100.00*(1+(2.0/100)) -- 100.00 comes from(ccp_id:1 and period=601)
},
{
"ccp_id":1,
"period":603,
"growth":3.0,
"sales":"NULL" ##sales=100.00*(1+(2.0/100))**(1+(3.0/100))-- 100.00 comes from(ccp_id:1 and period=601) 2.0 comes from (ccp_id:2 and period=602)
},
{
"ccp_id":2,
"period":601,
"sales":200.00
},
{
"ccp_id":2,
"period":602,
"growth":2.0,
"sales":"NULL" ##sales=200.00*(1+(2.0/100))
},
{
"ccp_id":2,
"period":603,
"growth":3.0,
"sales":"NULL" ##same like above
}
])
Run Code Online (Sandbox Code Playgroud)
并且我需要通过使用具有匹配条件ccp_id的上述文档来计算具有NULL的销售字段,并且期间字段应该等于601.我已经添加了一行来演示上面集合中的销售字段的计算.我试过$ graphlookup但没有运气.你们可以帮助或建议某种方式吗?
您可以使用以下聚合:
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 ] }] } ] }
}
}
}
}
}
}
])
Run Code Online (Sandbox Code Playgroud)
基本上要计算n-th元素的值,你必须知道以下事项:
$firstin $group)growths($pushin $group)n这表明你有多少次乘法执行要计算你应该索引$push的所有元素到一个数组,然后使用$unwind具有includeArrayIndex选项,它会插入unwinded数组的索引字段index.
最后一步计算累积乘法.它使用$ slice with indexfield来评估growths应该处理的数量.所以会有一个元素601,两个元素602等等.
然后是$ reduce处理该数组并根据您的公式执行乘法的时间:( 1 + (growth/100))
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |