How to use updateMany to update dates by adding days?

Hello! I am trying to update each of the dates of some documents by means of updateMany by adding a certain number of days, but I don’t know if it is not possible or if I am not doing something right, I leave you part of the code:

Exemple :
I have this document:

{
   appointmentObservations: "Hello",
   appointments: [
         {
          uid: '123445667',
          date: '2022-04-10T22:00:00.000Z'
         }
   ]
}
If i add 1 day i want this:
{
   appointmentObservations: "Hello",
   appointments: [
         {
          uid: '123445667',
          date: '2022-04-11T22:00:00.000Z' ======> one day added
         }
   ]
}

This is my trying:

await Appointments.updateMany(
    {
      "appointments.UIDRecurrent": uid,
      "appointments.date": { $gte: new Date(date) }
    },
    {
      "$set": {
        "appointmentObservation": appointmentObservation,
        "appointments.0.busyDays": busyDays,
        "appointments.0.recurrentTitle": recurrentTitle,
        "appointments.0.UIDRecurrent": UIDRecurrent,
        "appointments.0.date": {
          "$add": ["$appointments.0.date", 1000 * 60 * 60 * 24]
        }
      }
    })

What am I doing wrong? can it be done somehow?

Thank you very much!! :slight_smile:

Hi @Sergi_Ramos_Aguilo ,

Yes you need to use the $set in an aggregation update syntax with a new aggregation pipeline operator :

Now if you don’t have 5.0 let us know and we can give you some alternative.

Thanks
Pavel

Thank you for answer.
Ooh, the version I am using is 4.2.7 , what alternative is there in versions lower than 5.0?

Thank you again!

Hi @Sergi_Ramos_Aguilo ,

Well the apternative is a bit complex as you have a nested document that you need to update via an aggregation by adding date interval.

Something like the following should work:

.updateMany({
      "appointments.UIDRecurrent": uid,
      "appointments.date": { $gte: new Date(date) }
    }, [{$set: {
 appointmentObservation: appointmentObservation,
 appointments: {
  $map: {
   input: '$appointments',
   as: 'appointment',
   'in': {
    $mergeObjects: [
     '$$appointment',
     {
      busyDays: busyDays,
      recurrentTitle: recurrentTitle,
      UIDRecurrent: UIDRecurrent,
      date: {
       $add: [
        {
         $first: '$appointments.date'
        },
        86400000
       ]
      }
     }
    ]
   }
  }
 }
}}])

Place the needed variables, Notice that I map and merge documents i order to place the new date…

There might be another solution …

Thanks
Pavel

fantastic! Thanks a lot! works perfectly as I wanted

:slight_smile: :slight_smile:

Thank you!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.