乐闻世界logo
搜索文章和话题

How to group date quarterly wise?

1个答案

1

In Mongoose, to group dates by quarter, you need to use the Aggregation Framework for data processing. The Aggregation Framework enables you to perform complex data processing and transformation operations, including grouping, aggregation, and sorting. Here is an example illustrating how to use the MongoDB Aggregation Framework via Mongoose to group documents, with the date field used for quarter calculation:

javascript
const YourModel = require('path_to_your_model'); // Import your Mongoose model // Create an aggregation pipeline YourModel.aggregate([ { $project: { year: { $year: "$dateField" }, // Extract the year from the date field quarter: { // Calculate the quarter $ceil: { // Round up $divide: [{ $month: "$dateField" }, 3] // Divide the month by 3 } }, // Include other fields you need otherFields: 1 // 1 indicates inclusion of the field } }, { $group: { _id: { year: "$year", quarter: "$quarter" }, // Group by year and quarter count: { $sum: 1 }, // Calculate the number of documents per quarter // You can add other aggregation operations, such as averages, maxima, and minima. } }, { $sort: { "_id.year": 1, "_id.quarter": 1 } } // Sort by year and quarter ]) .then(results => { // Process the aggregation results console.log(results); }) .catch(err => { // Error handling console.error(err); });

In this aggregation pipeline, the $project stage is used to create the year (year) and quarter (quarter) fields. The quarter is calculated by dividing the month by 3 and rounding up. Subsequently, the $group stage groups by year and quarter and computes the count of documents per group. Finally, the results are sorted using the $sort stage.

This example assumes you have a Mongoose model YourModel and a date field dateField. You should adjust the code based on your specific model and field names. Additionally, the aggregation pipeline is flexible, enabling you to add other aggregation stages as required, such as filtering using $match or calculating other statistics.

2024年6月29日 12:07 回复

你的答案