Increment months to a date using an element attribute

Let’s say I have a collection of subscriptions as below:

    {
        "id": "8SDQ8"
        "durationInMonths": 12,
        "startDate": {
            "$date": "2020-07-03T09:14:46.609Z",
        },
        "endDate": {
            "$date": "2021-07-03T09:14:46.609Z",
        }
    }

How can I add $durationInMonths to a variable date without being forced to fetch $durationInMonths beforehand ? Something like this:

    const myDate = new Date();
    subs.findOneAndUpdate({
    	id: '8SDQ8'
    }, {
    	$set: {
    		startDate: myDate,
    		endDate: {
    			$addMonths(myDate, "$durationInMonths")
    		}
    	}
    });

Do you mean "how do I increment start date by 12 (or some arbitrary number of months) to get end date?

You can use aggregation pipeline update syntax (new in 4.2) like this:

[ {$set:{endDate:{$dateFromParts:{
      year:{$year:"$startDate"},
      month:{$add:["$durationInMonths", {$month:"$startDate"}]},
      day:{$dayOfMonth:"$startDate"},
      hour:{$hour:"$startDate"},
      minute:{$minute:"$startDate"},
      second:{$second:"$startDate"}
  }}}}
]
1 Like