Tuğrul Karakaya
Tuğrul Karakaya

Reputation: 111

Create MongoDb View from an aggregation with current date filter

I'd like to create a view from and aggregation which applies a datefilter using currentdate. in the given example below I use current date as string and works OK but I need to keep these dates updated automatically.

{
  $and: [{
      'promotionRange.start': {$lte:  ISODate('2019-11-12')}
      },
      {
      "promotionRange.end": {"$gte": ISODate('2019-11-12')}
      }
  ]
}

I need something like the code below

{
  $and: [{
      'promotionRange.start': {$lte:  $currentDate}
      },
      {
      "promotionRange.end": {"$gte": $currentDate}
      }
  ]
}

this does not work. and new Date() is also does not work.

Any tricks to use current Date in aggregation query?

Upvotes: 2

Views: 675

Answers (1)

Fraction
Fraction

Reputation: 12993

I don't think it is correct to use the same date in start and end dates, if you want to filter from the start of today to the current date/time you can retrieve the date part of the current date as a string using new Date().toISOString().slice(0,10) for the start date and for the end date use ISODate without argument :

const startDate = new Date().toISOString().slice(0,10); // "2019-11-13"

...


{
  $and: [{
      'promotionRange.start': {$lte:  ISODate(startDate)} // 2019-11-13T00:00:00Z
      },
      {
      'promotionRange.end': {$gte: ISODate()}
      }
  ]
}

Upvotes: 0

Related Questions