Muirik
Muirik

Reputation: 6289

Handling Mathematical Calculation in Mongo View

I'm aware of the basic mathematical operators you can use within a Mongo pipeline ($add, $multiply, $ceil, etc), but I have a situation where I want to calculate the number of days that have passed since a certain date that is recorded in the database. Normally I would do this by getting the difference in milliseconds between now and the recorded date, and then convert that back into a day, like so:

  let d = new Date();
  let todayValue = d.getTime();

  let visitDate = new Date(visitedAt); 

  let visitDateValue = visitDate.getTime();

  let diffSinceVisitDateValue = todayValue - visitDateValue;

  let durationOfVisitDiff = moment.duration(diffSinceVisitDateValue, 'milliseconds');
  let daysSinceVisitDecimal = durationOfVisitDiff.asDays();

  let daysSinceVisited = Math.round(daysSinceVisitDecimal);

But is there a way I can handle that calculation within the pipeline of my Mongo view? From my understanding, map/reduce is not an option in Mongo views. Which leaves me wondering if this kind of logic is possible within a Mongo view.

To clarify, this is a value that will only be in the Mongo View. This is not a field on the model.

Also, if there's another option, I'm open to hearing it if it will get the value into my mongo view.

Upvotes: 1

Views: 155

Answers (1)

hugomarisco
hugomarisco

Reputation: 336

This pipeline should do the trick:

[ { $addFields: { days: { $trunc: { $divide: [ { $subtract: [ new Date(), '$date' ] }, 86400000] } } } } ]

This is simply taking the Date stored and subtract it to the current date returning the difference in milliseconds. After that we just need to divide my 86400000 (ms in a day) and truncate the decimal part.

Note that I'm assuming the column is named 'date' and I'm creating a new column to hold the result called 'days'. Update it to fit your needs.

Upvotes: 2

Related Questions