How to include duration in a date field in MongoDB

Currently, I am working on honing my skills in mongodb and nodejs, but have encountered a hurdle along the way. Within my mongoDB database, there is a table named Schedule containing fields such as id, start, and end. My objective is to augment the start time of a specific row by a certain duration, provided that the start time is less than the end time.

For instance, consider the following entry in the Schedule table:

{
   "_id": "123", 
   "start": "2020-03-11T09:00:00.000Z", 
   "end": "2020-03-11T18:00:00.000Z"
} 

Let's assume we have a duration parameter of 30 minutes (30x60x1000ms). The desired outcome is as follows:

[
 {"id":1, "time":"2020-03-11T09:00:00.000Z"}, 
 {"id":2, "time":"2020-03-11T09:30:00.000Z"}, 
 {"id":3, "time":"2020-03-11T10:00:00.000Z"}, 
 {"id":4, "time":"2020-03-11T10:30:00.000Z"},   
 {"id":5, "time":"2020-03-11T11:00:00.000Z"},
 ...
 {"id":n, time:"2020-03-11T18:00:00.000Z}
]

I attempted to use the $add aggregation, but only managed to retrieve the first row.

const {idSchedule} = req.params;
const {duration} = req.body;
const durationMs = duration*60*1000;
console.log('duration',duration);
objId = new ObjectID(idSchedule); 
Schedule.aggregate([
   { "$match":{
        "_id": objId,
        }
    },
   { $project: { _id: 1, time: { $add: [ "$start", durationMs ] } } }
]).then((response) => {
    res.send(response)
})

However, the output I received was limited to:

[
 {
    "_id": "5e68ebf0992e173a28e7dd46",
    "time": "2020-03-11T09:30:00.000Z"
 }
]

Your assistance is greatly appreciated!

Answer №1

Feel free to utilize this method. The crucial operator to focus on is $map: { input: { $range: .... Initially, it's necessary to calculate the size (using $let) and then proceed with using $range to create the array:

db.collection.aggregate([
   {
      $set: {
         interval: {
            $let: {
               vars: {
                  size: {
                     $divide: [{ $subtract: ["$end", "$start"] }, { $multiply: [1000, 60] }]
                  }
               },
               in: {
                  $map: {
                     input: { $range: [0, { $add: ["$$size", 1] }, 30] },
                     in: {
                        id: { $add: [{ $divide: ["$$this", 30] }, 1] },
                        time: { $add: ["$start", { $multiply: [1000, 60, "$$this"] }] }
                     }
                  }
               }
            }
         }
      }
   },
   { $unwind: "$interval" },
   { $replaceRoot: { newRoot: "$interval" } }
])

Check out the Mongo playground for a live example.

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

How do I ensure my Node.js code waits for a pipe and createWriteStream operation to complete before moving on to the next lines of

Recently delving into Nodejs, I encountered a challenge. I am in the midst of saving a zip file from an S3 bucket to an EC2 instance that hosts my Nodejs service. The next step involves decompressing the zip file locally within the file system on the EC2 s ...

How can I prevent writeFileSync from replacing existing data?

When I use this line of code, it deletes all existing data. Is there a method or function that will append the new data on a new line instead? fs.writeFileSync(path.resolve(__dirname, 'quotes.json'), JSON.stringify(quotey)); ...

Node application running in Docker cannot establish connection with the Postgres database also running in Docker

I've experimented with various solutions, but none of them seem to work for me. Here's what I did: I set up a nodejs container and a postgres docker container. I used docker compose to configure both and a Dockerfile to build the nodejs/typescri ...

Searching with Mongoose using a specific field

When attempting to query the 'Order' mongoose object in express, I encountered an issue. Despite adding the querystring variable within the parentheses of the find method, the query did not work as expected. I am currently struggling with underst ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

Can someone explain the npm install messages from react-compare-app?

Scenario: I recently explored the react-compare-app example from React's examples page and decided to clone the repository. Following the usual procedure, I ran `npm install`. Initially, everything appeared normal as with most installations I have don ...

An Introduction to Integrating mySQL with Express and Node.js

Seeking guidance on integrating Node.js and Express with mySQL. I aim to create a basic application using these technologies but unable to find helpful tutorials so far. ...

Error in Node.js: Attempting to access property 'productId' of an undefined object

I'm grappling with performing relational operations using node.js. Order Schema: const mongoose = require("mongoose"); const orderSchema = mongoose.Schema({ product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product&apos ...

The redirection feature in nodejs/expressjs does not seem to function properly

I attempted to use the redirect function in expressjs to serve a webpage, but for some reason it's not functioning properly. I must be missing something here. index.html: <html> <body> <div id="clicked"> not clicked </div&g ...

Encountered an issue with Next.js error middleware where the response status is returning undefined

I have integrated next-connect into my next.js application for running server side code. I have implemented a custom error middleware, but it is throwing an error stating: res.status is undefined This is the implementation of my error middleware: export c ...

When using lambda functions with async.parallel, the last callback function may not be executed

I have created a lambda function in node.js with two files - index.js and loader.js. The problem I am facing is that the callback function in index.js is not being executed after the method in loader.js completes its execution. Below is the code: var yat ...

Exploring the contents of a directory and accessing files in nodejs

Here is the current code snippet: const fs = require('fs') fs.readdir('C:\Users\Eva\Desktop\Main\Input', (err, files) => { if (err) { console.log(err); return; } files.forEach(file => { ...

When attempting to install Electron using npm with the -g flag, an error occurred due to the inability to verify

The Issue at Hand I'm facing trouble while attempting to globally install Electron on my system using the command below: npm install electron -g However, I keep running into this frustrating error message: unable to verify the first certificate Here ...

What is the process for adding values to an existing JSON object in MongoDB?

I need to calculate the expenses for a specific category in a particular month. Below is an example of my data stored in MongoDB: { "2022":{ "January":{ "Food":30, "Traveling":0, ...

mysql nodejs function is returning a null value

Kindly review the contents of the dbfn.js file /*This is the database function file*/ var db = require('./connection'); function checkConnection(){ if(db){ console.log('We are connected to the Database server'.bgGreen); ...

What is the method for defining the maximum stack size in a node.js environment?

I encountered an error when trying to convert a docx file to epub format. Despite increasing the stack size, the task was unsuccessful. The specific error message I received is as follows: RangeError: Maximum call stack size exceeded at Array.filter (n ...

Why is my Node.js express application throwing a 404 POST error?

I am facing an issue while trying to build a node.js application with express. Whenever I attempt to log in and my index.ejs file sends a post request to the server, I encounter a 404 error. Being new to programming, I am seeking assistance from someone wh ...

An error message indicating that the page is currently being unloaded has appeared

While working on a NodeJS-ReactJS Isomorphic App, I encountered an issue when clicking on a Link. An error message popped up saying: Uncaught (in promise) Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by ...

WebStorm: Exploring HTTP server choices for both local development and cross-platform compatibility

Recently, I decided to give WebStorm 5.0 a try with AngularJS for testing purposes. However, I encountered an issue - I couldn't figure out how to set up or add a server for my HTTP files. Currently, I am using both a Windows 7 PC and a Mac. I' ...

Resolving the Node.js and MySQL duplication problem

Currently, I am utilizing the mysql module for nodejs and my application is functioning with multiple workers using the cluster package. Each worker retrieves tweets and saves them in the database, ensuring that each record is distinct based on the tweet_ ...