How to add days with dates while using updateMany?

Hello, I’m facing a problem with my query. I was trying to update some documents on MongoDB realm. I have a field ‘startDate’ and what I want is to add 5 more days with the startDate of the document. But its not working. I tried this:

  const reAdjustTargetDateOnDrop = async (
    targetStartDate: Date,
    track: string,
    studentId: string
  ) => {
    const result = await PICollection.updateMany(
      {
        trackNo: track,
        startDate: { $gte: targetStartDate },
        studentId: new Realm.BSON.ObjectID(studentId),
      },

      [
        {
          $set: {
            startDate: {
              $dateAdd: {
                startDate: "$startDate",
                unit: "day",
                amount: 5,
              },
            },
          },
        },
      ]
    );
    return result;
  };

I’m getting this error: “cannot transform type primitive.D to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel”

but when I try this :startDate: new Date(“2023-05-21”), this is working

Hi @Tanjil_Hossain and welcome to MongoDB community forums!!

If I understand the above statement correctly, are you trying to add days to the “starttDate” field of the document.
This would be possible using the aggregation using the $add operator by adding the specific milliseconds to the createdAt fields.

Based on the sample data provided:

date> db.sampleTest.insertOne( { "title": "Sample Document", "content": "This is a sample document with a Date field.", "createdAt": ISODate("2022-05-27T12:30:00Z")})
{
  acknowledged: true,
  insertedId: ObjectId("64622cf15d279eac2cd4f3a4")
}
date> db.sampleTest.aggregate( [ { $addFields: { NewDate: { $add: [ "$createdAt", 3*24*60*60000 ] } } }])
[
  {
    _id: ObjectId("64622cf15d279eac2cd4f3a4"),
    title: 'Sample Document',
    content: 'This is a sample document with a Date field.',
    createdAt: ISODate("2022-05-27T12:30:00.000Z"),
    NewDate: ISODate("2022-05-30T12:30:00.000Z")
  }
]
date>

Let us know if you have any further questions.

Regards
Aasawari