英文:
GroupBy and Sum in prisma
问题
Here is the translated code portion:
我有以下的Prisma架构用于MongoDB数据库
```javascript
model orders {
id String @id @default(auto()) @map("_id") @db.ObjectId
totalAmount Int
createdAt DateTime @db.Date
}
现在我想要根据日期进行分组,并按月份汇总,如下所示
{
"一月": 4567,
"二月": 7785
}
我尝试了以下文档中提到的方法,但它不起作用
const sales = await prisma.orders.groupBy({
by: ["createdAt"],
_sum: {
totalAmount: true,
},
orderBy: { createdAt: "desc" },
});
我该如何实现这个?
这是您要求的翻译部分。如果您需要进一步的帮助,请随时提问。
<details>
<summary>英文:</summary>
I have the following Prisma schema for MongoDB database
model orders {
id String @id @default(auto()) @map("_id") @db.ObjectId
totalAmount Int
createdAt DateTime @db.Date
}
Now I want to apply groupby based on dates and give the sum on the basis of month like
{
"january": 4567,
"February": 7785
}
I tried the following as mentioned in documentation but its not working
const sales = await prisma.orders.groupBy({
by: ["createdAt"],
_sum: {
totalAmount: true,
},
orderBy: { createdAt: "desc" },
});
How can I achieve this ?
</details>
# 答案1
**得分**: 0
以下是您要翻译的部分:
"Looks like there is not any solution in Prisma right now. So To achieve the desired result, I use Prisma to fetch the relevant data from MongoDB and then perform the grouping and summing on the retrieved data in JavaScript as follow.
```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());
```"
<details>
<summary>英文:</summary>
Looks like there is not any solution in Prisma right now. So To achieve the desired result, I use Prisma to fetch the relevant data from MongoDB and then perform the grouping and summing on the retrieved data in JavaScript as follow.
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());
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论