Retrieve documents from MongoDB that were created within the last week and return a count of 0 for any days in which no documents were created

I need to extract documents from the last 7 days stored in my Mongo Database.

I have successfully retrieved data in the desired format, where specific dates and the number of tickets created on those dates are returned:

{
    "datesUsed": {
        "startDate": "2022-04-02T14:42:14.223Z",
        "endDate": "2022-04-09T14:42:14.223Z"
    },
    "data": [
        {
            "date": "02/04/2022",
            "numOfTickets": 1
        },
        {
            "date": "03/04/2022",
            "numOfTickets": 1
        },
        {
            "date": "04/04/2022",
            "numOfTickets": 2
        },
        {
            "date": "06/04/2022",
            "numOfTickets": 1
        },
        {
            "date": "07/04/2022",
            "numOfTickets": 1
        },
        {
            "date": "08/04/2022",
            "numOfTickets": 2
        },
        { 
            "date": "09/04/2022",
            "numOfTickets": 1
        }
    ]
}

The issue arises when Mongo only returns data for days with documents created, leaving out days like 05/04/2022 when no document was created.

My goal is to include another JSON object that accounts for these missing days as well:

{
            "date": "05/04/2022",
            "numOfTickets": 0
}

This is what I currently have implemented:

const companyId = req.query.companyId;
    let dates = [];
    const data = [];
    // Last 7 days
    const endDate = new Date();
    const startDate = new Date(Date.now() - 604800000);

    // Retrieve tickets from the past 7 days
    const allCompanyTickets = await ticketModel
      .find({
        company_id: companyId,
        createdAt: { $gte: new Date(startDate), $lte: new Date(endDate) },
      })
      .sort({ createdAt: 1 });

      console.log(allCompanyTickets)

    // Add them to an array
    allCompanyTickets.forEach((ticket) => {
      dates.push(ticket.createdAt.toLocaleDateString());
    });

    // Calculate occurrences of days in the dates array
    function countOccurrences(arr) {
      return arr.reduce(function (a, b) {
        a[b] = a[b] + 1 || 1;
        return a;
      }, []);
    }

    // Construct an object based on the calculated data
    const datesOrdered = countOccurrences(dates);

    // Assign keys to the data and push it to a new array
    for (let key in datesOrdered) {
      const tempObj = { date: key, numOfTickets: datesOrdered[key] };
      data.push(tempObj);
    }

    res.status(200).json({ datesUsed: { startDate, endDate }, data: data });

Answer â„–1

Here is an example:

db.ticketModel.aggregate([
  {
    $set: {
      unusedDates: {
        $range: [0, { $dateDiff: { start: "$start", end: "$end", unit: "day" } }]
      }
    }
  },
  {
    $set: {
      unusedDates: {
        $map: {
          input: "$unusedDates",
          in: {
            date: {
              $dateAdd: {
                start: { $dateTrunc: { dt: "$used.startDt", unit: "day" }},
                unit: "day",
                amount: "$$this"
              }
            },
            ticketCount: 0
          }
        }
      }
    }
  },
  {
    $set: {
      data: {
        $filter: {
          input: "$unusedDates",
          condition: { $not: { $in: ["$$this.date", "$data.date"] }}
        }
      }
    }
  }
])

Check it out on Mongo Playground

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

Accessing JavaScript variables within Selenium

Currently utilizing Selenium Webdriver 2.0 to test an HTML page that incorporates an x.js file. Within x.js, the variable "price" is defined based on data entered from the HTML form and various Javascript calculations. In the HTML, the correct price valu ...

Attempting to generate a cost estimator, however, no results are showing up upon clicking the calculate button

Having based my code on a template and being fairly new to Javascript, I expected everything to work smoothly. However, upon testing it, I encountered an issue where nothing was displayed in the results boxes. My goal is to develop a pricing calculator th ...

Clearing Time Field Input in Safari

Recently, I've been utilizing the following HTML input element: <input type="time"> While testing it in both Chrome and Safari, I noticed that the clear field (cross button) is absent when using Safari. How can I make the cross button appear i ...

Utilizing Mongoose queries for asynchronous operations through promises

Currently, I am utilizing Mongoose to establish a connection with MongoDB. It is mentioned that "Mongoose queries are not promises. If you require a complete promise, make use of the .exec() function." http://mongoosejs.com/docs/promises.html var promise ...

Troubleshooting issue with jQuery datepicker not triggering onselect event

Query Function: $(function() { $("#iDate").datepicker({ dateFormat: 'dd MM yy', beforeShowDay: unavailable onSelect: function (dateText, inst) { $('#frmDate').submit(); } }); }); HTML ...

Integrating threejs dynamically into a Create React App environment

When I am dynamically loading Three.js, the variable THREE is not found. I have created a React project using create-react-app and copied the three js file into the public folder. Here's the directory structure: src public ├── js │ └─┠...

What exactly do `dispatch` and `commit` represent in vuex?

Recently, I came across a Typescript project in Vue.js with a Vuex store that had the following code: async getUserProfile ({ dispatch, commit }: any) {} I found working with any cumbersome as it doesn't provide helpful autocomplete features in the ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...

Are the commands overlapping?

Currently, I am in the process of developing a dynamic discord chat bot using JavaScript and node.js. One of my goals is to implement a specific command without interfering with an existing one. The bot functions flawlessly across all servers where it is ...

The functionality of the WordPress Contact Form 7 Plugin becomes erratic when integrated into dynamically loaded AJAX content

I am currently facing a challenge with integrating the WordPress Contact Form 7 Plugin into a website I have built on WordPress. The theme of the site utilizes jQuery to override default link behavior and AJAX to load pages without refreshing the entire pa ...

Activate the front camera on an Android device using HTML5 or JavaScript

I'm currently working on a web app that needs to access the front camera of Android phones running version 4.0 or higher. After taking a picture, the app should then upload the captured image to my own server. Is there a way to launch the front camer ...

Having trouble loading the DOM element within the child component

An issue has arisen with Angular 4.4.6 regarding the access of a DOM element by ID from a different component. Within my component, I aim to display a Google Maps for specific purposes. Following the examples given in the API, I include the following code ...

The stunning fade effect of Magnific Popup enhances the visual appeal of the inline gallery

I'm currently using magnific popup for an inline gallery, but I'm not seeing any effects. I would like to have a fade effect when opening/closing the popup. Can someone assist me with achieving this? https://jsfiddle.net/gbp31r8n/3/ [Check o ...

Different body background color changes every second

I have a function called makeRandColor that generates a random color using RGB and template string literals. However, I am struggling to figure out how to make it work every second. I tried using setInterval but it doesn't seem to be functioning prope ...

Exploring cross-browser compatibility with the use of CSS3 and JavaScript

Starting a new project to create a fresh website. It seems like many people are leaning towards CSS3 and AJAX, neglecting browsers without JavaScript support. They resort to workarounds like enabling CSS3 through JavaScript in older browsers. Is this the ...

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

The use of WebSockets in conjunction with text encoding techniques

After reviewing the material, I came across this information: The WebSocket API allows for the use of a DOMString object, which is transmitted in UTF-8 format, or it can also accept an ArrayBuffer, ArrayBufferView, or Blob objects for binary data transf ...

Invoking a Vue method within a Laravel blade template

In my Laravel project, I have a blade that is loading a Vue component successfully. However, I am facing an issue where calling a method in the Vue component from a select box in the blade is not working as expected. Despite having a method call set up to ...