Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-10651

Aggregation expressions to add/subtract Years/Quarters/Months

    • Query Execution
    • Fully Compatible

      Update March 8, 2018

      As of 3.7.3 via SERVER-30523 $dateFromParts allows constructing a date by adding or subtracting to/from existing month or day values, including handling overflow/underflow to get a valid date that's N months ago or from now, or N days ago or from now (same for years, hours, minutes, etc).

      This ticket will track adding syntactic sugar to allow more straight forward syntax for such date operations as adding or subtracting days, months, hours, etc from another date.

      There is currently no approved syntax, see below for proposed syntax.

      Update May 1, 2014

      Since our Date type assumes that days are fixed at 86400 seconds, it is already possible to use $add and $subtract time units up to a week since they are all a fixed number of milliseconds. Year/Quarter/Month are more complicated because they are not fixed units of time. Additionally they probably shouldn't use $add or $subtract syntax since they do not follow the usual mathematical laws. For example, 2012/02/29 + 1 year is either 2013/02/28 or 2013/03/01. Either way, subtracting 1 year from that does not get you back to 2012/02/29. These are the sorts of questions we will need good answers to before we can tackle this ticket.

      Original Description

      It would be nice to count with something like DATE_ADD and DATE_SUB of MySQL where you can add or subtract intervals, not only milliseconds like the $add expression is doing now.
      Right now all the add/subtract operations with date are handled like numbers, and some cases this is not enough, like adding months or years.

      I propose to create new expressions to handle date addition/subtraction supporting units and also milliseconds. Like:

      db.test.aggregate( { $project: { expiryDate: { $dateAdd: [ "$date", [5, "months"] ] } } });
      db.test.aggregate( { $project: { lastYear: { $dateSub: [ "$date", [1, "years"] ] } } });
      

            Assignee:
            backlog-query-execution [DO NOT USE] Backlog - Query Execution
            Reporter:
            dribba David Ribba
            Votes:
            5 Vote for this issue
            Watchers:
            15 Start watching this issue

              Created:
              Updated:
              Resolved: