gpt4 book ai didi

Mongodb计算查询--累积乘法

转载 作者:IT老高 更新时间:2023-10-28 13:26:26 26 4
gpt4 key购买 nike

我最近开始在 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
}
])

并且我需要使用上述文档计算具有 NULL 的销售字段,匹配条件的 ccp_id 应该相同,期间字段应该等于 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 ] }] } ] }
}
}
}
}
}
}
])

基本上要计算 n-th 元素的值,您必须知道以下几点:

  • 第一个元素的销售额($group 中的$first)
  • 所有增长的数组($group中的$push)
  • n 表示你必须执行多少次乘法

要计算索引,您应该将所有元素$push 放入一个数组中,然后使用$unwind使用 includeArrayIndex 选项将展开数组的索引插入到字段 index

最后一步计算累积乘法。它使用 $slice使用 index 字段来评估应该处理多少 growths。所以601会有一个元素,602会有两个元素,以此类推。

那么该是 $reduce 的时间了处理该数组并根据您的公式执行乘法: (1 + (growth/100))

关于Mongodb计算查询--累积乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49430905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com