在我的mongodb数据库中,我有如下数据:
{ id: 'ran1', code: 'ABC1', createdAt: 'Sep 1 2022', count: 5 }
{ id: 'ran2', code: 'ABC1', createdAt: 'Sep 2 2022', count: 3 }
{ id: 'ran3', code: 'ABC2', createdAt: 'Sep 1 2022', count: 2 }
{ id: 'ran4', code: 'ABC1', createdAt: 'Oct 1 2022', count: 1 }
{ id: 'ran5', code: 'ABC1', createdAt: 'Oct 2 2022', count: 2 }
{ id: 'ran6', code: 'ABC2', createdAt: 'Ocr 1 2022', count: 1 }
现在,作为输出,我需要10月份的所有数据,但我还需要计算和比较百分比。
{code: 'ABC1', totalCount: the sum of total count of oct (1+2) =3 , percent: (total count of oct - total count of sep)/total count of oct * 100 }
{code: 'ABC2', totalCount: 1, percent: -100}
我尝试使用两个不同的聚合来实现这些输出,然后将当前月份的聚合与上个月聚合中的每个元素进行Map。
这是我的代码
const { filterDate, shop } = req.query;
const splittedFilter = filterDate.split("-");
const query = {
shopUrl: { $regex: shop, $options: "i" },
createdAt: {
$gte: new Date(splittedFilter[0]),
$lte: new Date(splittedFilter[1]),
},
};
const currentCodes = await BlockedCode.aggregate([
{
$match: query,
},
{
$group: {
_id: "$discountCode",
totalCount: { $sum: "$count" },
},
},
]);
const prevQuery = {
shopUrl: { $regex: shop, $options: "i" },
createdAt: {
$gte: new Date(splittedFilter[2]),
$lte: new Date(splittedFilter[3]),
},
};
const previousCodes = await BlockedCode.aggregate([
{
$match: prevQuery,
},
{
$group: {
_id: "$discountCode",
totalCount: { $sum: "$count" },
},
},
]);
const result = currentCodes.map((code) => {
const foundPrevCode = previousCodes.find((i) => i._id === code._id);
if (foundPrevCode?._id) {
const prevCount = foundPrevCode?.totalCount;
const currCount = code?.totalCount;
const difference = currCount - prevCount;
const percentage = (difference / currCount) * 100;
return { ...code, percentage };
} else {
return { ...code, percentage: 100 };
}
});
1条答案
按热度按时间vi4fp9gy1#
@shahamar Rahman我不明白百分比逻辑,你能多解释一点吗?
到目前为止,我过滤和计算的数据基于10月的一个月,请检查它,让我知道如果它的帮助你
https://mongoplayground.net/p/Fet3UUI9LDC