"Utilizing GroupBy and Sum functions for data aggregation in Prisma

I am currently working with a Prisma schema designed for a MongoDB database

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

My goal is to perform a groupby operation based on dates, and calculate the sum of total amounts on a monthly basis. For example:

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

I attempted to achieve this using the method provided in the documentation, but unfortunately, it did not work as expected:

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

Can someone guide me on how I can successfully accomplish this task?

Answer №1

It appears that Prisma does not currently offer a solution for this issue. In order to achieve the desired outcome, I utilized Prisma to retrieve data from MongoDB and then performed the necessary grouping and summing operations in 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());

Answer №2

If you're ever in need of aggregating data with GroupBy using a sum, the Prisma documentation offers some helpful guidance on how to achieve this.

Check out the Prisma docs

While it may not directly address the issue of monthly aggregation, Prisma makes it easy to handle sum and grouping operations seamlessly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences in SVG rendering between Chrome and Firefox

I am eager to create a diagram on my website using SVG. To ensure the diagram is displayed in full screen, I am utilizing availHeight and availWidth to determine the client screen's height and width, then adjust the scaling accordingly. My current sc ...

Yaml scripting for BunJs CLI commands

Are there any CLI tools in bun.js that are capable of interpreting Yaml scripts? Similar to how npm processes package.json files in node.js, allowing script definition and execution from the command line interface, but with Yaml being a more readable form ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

Showcasing two sets of data from an array using chart.js within a node.js environment

I am currently working on a project where I need to display two elements from an array - one as the label (e.g. "name of certain type of crop") and the other as the data itself (e.g. "quantity of the crop"). However, I am facing an issue where if the same ...

The issue I am facing is that when I click on a checkbox, only one of them seems to respond

When I click the button, only the first checkbox event is being checked while the rest of them are not. Can someone please provide some guidance on how to fix this issue? $("#cascadeChange").click(function() { //alert("Clicked"); ...

Retrieve information using an AJAX call

There is JSON data stored in a file that I need to read. The correct file data is printed to the console.log. What steps should I take to assign this data to variable x? Currently, when I execute the code, x ends up being undefined. function getData() { ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

Tips for creating a Material UI (next) dialog with generous top and bottom margins that extend off the screen

I am encountering a challenge with the layout. What am I looking for? I need a modal dialog that expands vertically, extending beyond the screen, centered both horizontally and vertically, with minimal margin on the top and bottom. Is this feature not d ...

I am a newcomer to HTML and I am eager to display the selected options from a <select> element

Can someone help me display the selected licorice flavor, chocolate color, and topping? For example: "Green apple, white, christmas sprinkles." I'm not sure if assigning a numeric value to each option is necessary. I did it on a whim. Please suggest ...

Drop down menus fail to appear after the screen has been resized

Creating responsive menus involves using ordered and unordered lists, along with CSS for styling. I have added a script to dynamically generate dropdown menus, but encountered an issue where nothing appears on the screen upon resizing - only the backgrou ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

Steps for configuring jQuery hide(), adding Class, and remove Class for flawless execution

My HTML Code is structured as follows : ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode'].'#' ...

Display Numerous Values Using Ajax

Having difficulty showing data from the 'deskripsisrt' table in a modal bootstrap? I have successfully displayed from the 'srtptr' table, but not sure how to proceed with the 'deskripsisrt' table. Here's a snippet from my ...

Troubleshooting why content set to a <div> element with JavaScript / jQuery is not persisting after a

This is the current code snippet I am working with: <asp:Button ID="btnSave" runat="server" OnClick="Save" CssClass="StylizedButton" resourcekey="btnSave" /> <div id="lbltot"></div> Below is the JavaScript portion of the code: $(do ...

How can we deliver pure JS, HTML, and CSS content without relying on static HTML pages?

Looking to create a fast app prototype without using React or Vue? I'd like to avoid simply making an html and js file imported within it. Can npm packages, SCSS be used while programming vanilla Javascript minus a framework? ...

The NextSJ configuration error: Webpack encountering a ModuleParseError due to an unexpected character in the module parsing process

I encountered an error while trying to build my Next.js app or start the server using the `yarn dev` command. This issue seems to have arisen after installing and then uninstalling the next-less plugin. I've tried reverting the code back to its previo ...

Tips for incorporating an onClick event into a variable beyond the class extension

Currently utilizing React/Redux in this scenario. At the beginning of my code, outside of the class extends block, I have: const Question10 = () => (<div> <p>Insert question here</p> <input place ...

Sorting functionality in Dyntable is not functioning properly when called from an Ajax request

I can't seem to get DynaTable with Ajax to work properly. Sorting, searching, and pagination are not functioning as expected. When I click on the column header, nothing changes in my table. Could someone please assist me? Below is my code snippet: H ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...