prisma 中的 GroupBy 和 Sum

问题描述 投票:0回答:2

我有以下 MongoDB 数据库的 Prisma 架构

model orders {
  id             String              @id @default(auto()) @map("_id") @db.ObjectId
  totalAmount    Int
  createdAt      DateTime            @db.Date
}

现在我想根据日期应用 groupby 并根据月份给出总和

{
  "january": 4567,
   "February": 7785
}

我尝试了文档中提到的以下方法,但它不起作用

const sales = await prisma.orders.groupBy({
    by: ["createdAt"],
    _sum: {
      totalAmount: true,
    },
    orderBy: { createdAt: "desc" },
  });

我怎样才能实现这个目标?

javascript mongodb next.js prisma
2个回答
1
投票

目前Prisma 中似乎没有任何解决方案。因此,为了达到预期的结果,我使用 Prisma 从 MongoDB 中获取相关数据,然后在 JavaScript 中对检索到的数据进行分组和求和,如下所示。

const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function sumTotalAmountByMonth() {
  const orders = await prisma.orders.findMany();

  const salesByMonth = orders.reduce((result, { createdAt, totalAmount }) => {
    const month = createdAt.toLocaleString('default', { month: 'long' });
    result[month] = (result[month] || 0) + totalAmount;
    return result;
  }, {});

  return salesByMonth;
}

sumTotalAmountByMonth()
  .then((salesByMonth) => console.log(salesByMonth))
  .catch((error) => console.error(error))
  .finally(() => prisma.$disconnect());

0
投票

对于将来想要使用求和在 GroupBy 上进行聚合的任何人,Prisma 文档提供了如何执行此操作的有用示例。

https://www.prisma.io/docs/orm/prisma-client/queries/aggregation-grouping-summarizing#order-by-aggregate-group

这并不能真正解决这里的问题,因为他们想要按月进行聚合,我不知道如何做到这一点,但是求和和分组部分可以由 Prisma 自动完成。

© www.soinside.com 2019 - 2024. All rights reserved.