What is the process for retrieving data from MongoDB for a specific month using Node.js?

I have a scenario where I need to retrieve data for a specific month. How can I determine the start and end dates of a given month?

Here is a snippet of the code:

{"_id":"5e00bc55c31ecc38d023b156","heat":20,"humidity":10,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-23T13:08:37.841Z"},
{"_id":"5e00bbd2c31ecc38d023b155","heat":20,"humidity":10,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-23T13:06:26.366Z"},
{"_id":"5df4a8fb46b9da1e2c0731df","heat":88,"humidity":80,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-14T09:18:51.892Z"},
{"_id":"5e00b50bc127260398cf51dd","heat":20,"humidity":10,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-23T12:37:31.127Z"},
{"_id":"5df20e44e7c51b4bd0095af3","heat":41,"humidity":26,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-12T09:54:12.375Z"}

Code snippet without using moment.js

Payload:

{
    "deviceId":"a-1",
    "year":2019,
    "month":"December"
}
Collection.aggregate([
  {
    $match: {
              "deviceId": payload.deviceId,
              "entryDayTime": {
                                $lt: new Date(`${payload.month},${payload.year},2`).toISOString(),
                                $gte: new Date(`${payload.month},${payload.year},31`).toISOString()
                              }
            }
  }
])

The time ranges obtained in console (times passed in the aggregate function) are as follows:

2019-12-01T18:30:00.000Z

2019-12-30T18:30:00.000Z

Code snippet using moment.js

Payload:

{
    "deviceId":"a-1",
    "year":2019,
    "month":10
}

I also attempted to use moment.js. However, the times generated do not match the database's time format.

Collection.aggregate([
  {
    $match: {
              "deviceId": payload.deviceId,
              "entryDayTime": {
                 $lt:moment([payload.year]).month(payload.month).startOf('month').tz('Asia/Kolkata').format(),
                 $gte:moment([payload.year]).month(payload.month).endOf('month').tz('Asia/Kolkata').format()
               }
            }
  }
])

The timestamps displayed in console are:

2019-11-01T00:00:00+05:30
2019-11-30T23:59:59+05:30

If moment.js is the preferred option, how can the time format be modified to match the time format in the sample code?

Answer №1

Here is a simple code snippet to try:

var date="2019-11-01T00:00:00+05:30";
var newDate= new Date(date);
var result= newDate.toISOString();
console.log(result);

Output :

'2019-10-31T18:30:00.000Z'

The toISOString() function returns a string in a standard format (ISO 8601) with a fixed length of 24 or 27 characters (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ respectively).

It always represents the time in zero UTC offset, indicated by "Z" at the end.

Answer №2

If you need to retrieve data for a specific month, you can utilize the Date.UTC method along with the Date constructor to establish a date range:

const payload = {
    "deviceId": "a-1",
    "year": 2019,
    "month": 11 // Please note that months range from 0 (January) to 11 (December) 
}

const from = new Date(Date.UTC(payload.year, payload.month, 1)).toISOString(); // "2019-12-01T00:00:00.000Z"
const to = new Date(Date.UTC(payload.year, payload.month + 1, 1)).toISOString(); // "2020-01-01T00:00:00.000Z"

You can then utilize these dates in the following manner:

Collection.aggregate([
  {
    $match: {
       "deviceId": payload.deviceId,
       "entryDayTime": {
          $lt: to,
          $gte: from
       }
    }
  }
])

Here's a practical example : https://mongoplayground.net/p/jkIJdJ-L7q-

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 difficulty merging information from one mongoose model to another

Novice Developer here. I am currently working with 2 schemas: var categorySchema = new mongoose.Schema({ name: String }); var subCategorySchema = new mongoose.Schema({ name: String, parent: { name: String, id: { ...

Adding a panel dynamically with Bootstrap incorrectly

I have been using the Collapse panel in Bootstrap and it was working perfectly when implemented statically. However, I encountered an issue when trying to add it dynamically. HTML <form> <div class="form-group" > <label for="c ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Transform the Curly Braces within a string into an HTML span Element using JSX

Looking to parameterize a string like 'Hello {name}, how are you?' in React Component? Want to replace curly braces with variable text and highlight it using span/strong tag. Here's an example of the desired final result: Hello <span cla ...

Preventing duplication of code execution in recycled PHP elements

Currently, I have implemented a generic toolbar that is used on multiple pages of my web application by using PHP include. This toolbar contains log in/log out functionality and checks the log in status upon loading to update its UI accordingly. Initially ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...

Struggling to retrieve information from session storage to pass along to a PHP class

Is there a way to fetch the email of the currently logged-in user from sessionStorage and send it to a PHP file? I have tried implementing this, but it seems to be not functioning properly. Could you assist me in resolving this issue? <?php $mongoCl ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

Is it possible to include parameters within a print() function in JavaScript?

Can anyone help me figure out how to add parameters to a print function? I only want to print a specific table, but when I try to print it, the entire page gets printed instead. Here's my code: let tableContent = document.getElementById('tablen ...

What is the correct way to end this jQuery statement?

I've been working on this for about 6 hours now. I ran it through multiple Lint tools and various other online tests, but I just can't seem to get the statement below to close properly. There's a persistent error showing up on the last line ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

What is this error: "Unknown authentication strategy 'loca'"?

Whenever I try to utilize passport.js, it keeps throwing the following error: Unknown authentication strategy "local"! config/configuration.js var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; ...

Issue regarding Jquery widget

I am working with a widget that looks like this $.widget("ui.myWidget", { //default options options: { myOptions: "test" }, _create: function () { this.self = $(this.element[0]); this.self.find("thead th").click(fun ...

Utilizing the loop counter within an Array

Currently, I am attempting to iterate through numbers 1 to 21 and then utilize those numbers in order to obtain an Array of Strings like ['e1.wkh',...'e21.wkh']. However, at the moment I am only receiving the value ['e21.wkh'] ...

Uncovering the Secrets of Retrieving Nested Objects with MongoDB and Mongoose

I have a collection of documents stored in my mongodb database, each structured like this: { "current" : { "aksd" : "5555", "BullevardBoh" : "123" }, "history" : { "1" : { "deleted" : false, ...

Typescript: Securing Data with the Crypto Module

I am currently working on encrypting a password using the built-in crypto module. Previously, I used createCipher which is now deprecated. I am wondering if there is still an effective way to achieve this. Here is the old code snippet: hashPassword(pass: ...

Utilizing Angular's asynchronous validators to handle incoming response data

Struggling with async validators in Angular and trying to implement Container/Presentational Components architecture. Created an async validator to check for the existence of an article number, with the service returning detailed information about the arti ...

Real-time console input/output feature for a gaming server utilizing either JavaScript or PHP

About My Minecraft Server: After running a Minecraft server in my basement for a few months, I realized that using TeamViewer to input commands and monitor the console was not ideal. The console of a Minecraft server provides a log of events with timestamp ...

Implementing dynamic controls in an ASP.NET MVC5 application using AngularJS

I am currently working on a project that will utilize MVC5, angularJS, and bootstrap for development. One of the key features in my project is a dropdown menu called "expense type". Upon selecting a value from this dropdown, additional controls need to be ...

What could be the reason for JavaScript delaying the execution of DOM statements until a variable is true?

Today I've been tackling numerous bugs, but there's one particularly tricky bug that has me stumped. The snippet of code below pertains to a basic logon page. Currently, the only valid username is 'admin' and the corresponding password ...