2

I am trying to update a date field (say nextChargeDate) in multiple documents in a collection with another date field (say currentTermEndDate) in the same document incrementing the currentTermEndDate by 1 day.

Here's the update function I have written:

db.some_collection.updateMany(

{$or: [{_id: ObjectId('5c3e62ef2e9c4e0008f4749f')}, {_id: ObjectId('5c3e635a2e9c4e0008f47852')}, {_id: ObjectId('5c3e63a12e9c4e0008f47ab9')}]},
{
    $set: { **nextChargeDate: new Date({$add: [ "currentTermEndDate", 1*24*60*60000 ]}**)  }
}

)

Here's the update looks like in Mongo:

currentTermEndDate:2019-04-04 23:59:59.999

nextChargeDate:1969-12-31 18:00:00.000

It would be very helpful if someone can help with a solution to achieve the desired result which would be:

currentTermEndDate:2019-04-04 23:59:59.999

nextChargeDate:2019-04-05 23:59:59.999

Thanks in advance.

SandipSau
  • 21
  • 4
  • Possible duplicate of [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) – Arsen Davtyan Feb 10 '19 at 06:10
  • 2
    I went through the information in the above link but that was for a string field and in my case its date field and I need to perform this operation for particular set of documents filtered by the query mentioned above. I am not sure how I can perform aggregation on a particular set of documents and not all. If someone can provide a sample code would help me to better understand. I am new to Mongo DB – SandipSau Feb 10 '19 at 06:50

1 Answers1

-1

You need to take a date as ISODate("dateField").getTime(). Try below query:-

    {$or: [{_id: ObjectId('5c3e62ef2e9c4e0008f4749f')}, {_id: ObjectId('5c3e635a2e9c4e0008f47852')}, {_id: ObjectId('5c3e63a12e9c4e0008f47ab9')}]},
{
    $set: { "nextChargeDate": new Date(ISODate("currentTermEndDate").getTime()+ 1*24*60*60000)  }
}
Nishant Bhardwaz
  • 924
  • 8
  • 21
  • Hello @cogent, I tried the query as mentioned above $set: { nextChargeDate: new Date(ISODate("currentTermEndDate").getTime() + 1*24*60*60000) But I am getting this error: 2019-02-10T18:13:17.712-0600 E QUERY [js] Error: invalid ISO date: currentTermEndDate : ISODate@src/mongo/shell/types.js:65:1 – SandipSau Feb 11 '19 at 00:20
  • The date format is `Date` in the DB here's a sample: currentTermEndDate: 2019-01-16 23:59:59.999 nextChargeDate: 2021-01-18 00:00:00.000 – SandipSau Feb 11 '19 at 14:51