Home > database >  mongo aggregation to add deleted at field to query
mongo aggregation to add deleted at field to query

Time:05-26

I want to use a mongo aggregation to add a field to the document that lets me know when a document "should" be deleted. specifically i want the document to be deleted after 30d, which isnt hard, the function that handles deletion is pretty straightforward, however i want to be able to tell the client, when this object will be deleted. as in if i created the document on the first its scheduled deletion date will be the 30th. Id like to latch on to the createdAt field, and simply just add 30d to it. the hang up is making that happen, id like for it to do this as it pulls the documents out (since they are pulled out in an array) instead of looping over the array and modifying each field.

here is the current code for the aggregate

{
  $addFields: {
     deletedAt: "$createdAt"   Date("$createdAt"   30),
  },
},

CodePudding user response:

You can do that with $dateAdd operator

{
    $addFields: {
      deletedAt: {
        $dateAdd: {
          startDate: '$createdAt',
          unit: 'day', // this also can be years, days, minutes and so on
          amount: 30 // the amount to add based on the unit
        }
      }
    }
}
  • Related