Find the difference in weeks between two dates using MongoDB aggregate

My current dilemma involves extracting student data for each week within an academic year based on a start date and end date. To achieve this, I have devised an array that contains the start and end dates for every week. The process involves iterating through each week, querying the database in a loop like so:

let allWeeksData = []

  let groupQuery: any = {
    _id: {
      attendance_code: "$attendance_code",
    },
    total: { $sum: 1 },
  };

for(let dateRanges of dateRangesArray)
{
  const startDate = dateRanges.start_date;
  const endDate = dateRanges.end_date;

  const rawResults = await sessionAttendanceModel.aggregate([
    {
      $match: {
        student_school: { $in: studentSchoolIDs },
        "date.date": {
          $gte: new Date(startDate),
          $lte: new Date(endDate),
        },
        attendance_code: {
          $in: usedAttendanceCodes,
        },
      },
    },
    {
      $group: groupQuery,
    },
  ]);
  rawResults.start_date = startDate
  rawResults.end_date = endDate
  allWeeksData.push(rawResults)
}

However, this method has proven to be inefficiently slow. Is there a more streamlined approach to execute a single aggregate group query on the database and achieve the same outcome?

Answer №1

If you need to extract the week of the year from a date in MongoDB, you can utilize the $week operator. By incorporating a $group stage, you can easily group your data based on the weeks of the year:

{
  $group: {
    _id: {
      "week": {
        $week: "$date"
      },
      "year": {
        $year: "$date"
      }
    }
  }
}

Explore this concept further with the help of the Mongo playground

Answer №2

Consider organizing the data like this:

{
   _id: {
      event_type: "$event_type",
      time: {
         $dateTrunc: {
            timestamp: "$timestamp.timestamp",
            unit: "hour",
            startOfHour: "midnight"
         }
      },
   },
   count: { $sum: 1 },
}

Answer №3

If you want to organize your data by weeks, you can use the $group function and then customize the exit values in the $project pipeline to fit your specific requirements.

Your aggregation operation should look something like this:

[{
    $group:{
        _id:{
            $week: "$date.date"
        },
        data:{
            $first: "$$ROOT"
        }
    }
}]

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

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...

Switching the theme color from drab grey to vibrant blue

How can I change the default placeholder color in md-input-container from grey to Material Blue? I have followed the instructions in the documentation and created my own theme, but none of the code snippets seems to work. What am I doing wrong? mainApp. ...

Locate a value in a MongoDB dictionary using a filter operation

My MongoDB database has the following data structure: {'_id':'...', 'friends': {'id1': {'name1':'value1', 'name2':'value2'}, 'id2': {'name ...

Running a Chrome content script once an AJAX request has been triggered by the <body> element

I am facing a challenge with running the content script before the DOM is fully loaded. To give context, there is an AJAX request within a tag which gets triggered on $(document).ready(). Once this request is completed, my extension code kicks in. To tra ...

How to modify the placeholder attribute value using jQuery

i have a table $(document).ready(function() { $('#f05_0002').change(function() { if ($("#f05_0002").val() == "OFF TRACK") { $("#f06_0002").attr("placeholder", "Please specify what has not been achieved and provide recommenda ...

Automatically omitting a selector that mimics a switch

After conducting thorough research, I discovered a variety of solutions using jQuery and Vanilla. While one answer perfectly addressed my issue, it failed to integrate effectively with the rest of my code. So, I decided to modify the code from this Stack O ...

Undefined properties appear in Mongoose model after population process

I am facing an issue with a basic request. When I fetch all properties of a mongoose model, they are coming up as undefined in the exec() callback. Below is my schema : userSchema: new Schema({ email: { type: String, limit: 50, index: true }, pas ...

After making a POST request, I must ensure that the page is rendered accordingly

How can I efficiently handle requests to the server and update the page without reloading it, following SPA principles using useEffect()? I attempted to implement something like this: useEffect (() => { addProduct (); }) but it proved to be ineffectiv ...

Can the submit ID value be utilized in PHP?

name="submit" functions as expected. if(isset($_POST["submit"])) <input type="submit" ID="asdf" name="submit" value="Save" class="ui blue mini button"> I want to change it to use ...

The functionality of the button is disabled once a pop-up JavaScript is implemented

I have encountered an issue with my HTML code that involves a button intended to hide certain content. The problem arose when I implemented a popup feature, causing the button to malfunction. Here is the JavaScript for the popup: $ = function(id) { retur ...

Calculate the total number of randomly generated integers using jQuery

Below are examples of the inputs I have generated: <input type="text" id="rfq_ironilbundle_quotes_offer_price_0" name="rfq_ironilbundle_quotes[offer_price][0]" required="required" class="form-control offered-price"> <input type="text" id="rfq_iro ...

Creating a draggable element in JavaScript using React

I've been attempting to create a draggable div element, but I'm encountering some perplexing behavior. The code I'm using is directly from w3schools and it functions correctly for them, however, in my implementation, the div always shifts to ...

Intersecting object identification, fresh Function

I'm currently utilizing the "Sinova / Collisions" library on GitHub along with Node.js. The library can be found at https://github.com/Sinova/Collisions. I am in need of a function that allows me to delete all data at once, as the current function for ...

Which behaviors that are typically exhibited by browsers will be stopped by calling `event.preventDefault()`?

While I grasp that using event.preventDefault() stops default actions triggered by events in the browser, I find this explanation too general. For instance, what exactly are these default event behaviors in the browser? It's common to see developers u ...

step by step guide on populating dropdown options with ajax in spring mvc

I am new to using ajax and spring mvc. I successfully retrieved data from my MongoDB database via an ajax call. Now, I need assistance with setting dropdown values based on the ajax object. home.jsp <select class="form-control" id="list1value"> &l ...

guaranteed function to retrieve React elements

Is there a solution for the issue where if-else doesn't work in run build but works in run dev? The only way I've found to make it work is by using a react hook, but I'm unsure which one to use and where to implement it. import { useAdd ...

Achieve iframe resizing using only pure JavaScript, no reliance on jQuery required

I have a question about an iframe on my webpage. <iframe class="myframe" src="some_page.html" width="800px" height="600px" /> Is there a way to make this iframe resizable like the <textarea></textarea> tag? I prefer to achieve this wit ...

Preventing Jquery Append from Adding Previous Elements

I am struggling to figure out how to display the star rating for each hotel individually. I have 5 hotels, each with a different star rating. Here is my Javascript code: function GetStarHotel() { var parent = $(' p.star '), imagePat ...

Jest test failing due to issues with a stateful React component containing an asynchronous function

I'm currently going through a Jest testing tutorial on Pluralsight that can be found here. Even though I have written the code exactly like the author, my test is not passing for some reason. Link to my Pull request on the author's repo: https:/ ...