Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a day to a Date in MongoDB

How can I increment a date by 7 days in a document without having to manually set the date?

Collection Data:
{
    "_id" : ObjectId("5e302f83edd1fd00125abbf9"),
    "dateTransferred" : 2020-01-26T00:00:00.000+00:00
}

I can easily update the collection by using:

db.data.updateMany(
  {},
  {
    "$set": { "dateTransferred": new ISODate("2020-02-03T03:34:54Z") }
  }
)

Is there a way I can update it dynamically (Similar to DateAdd)

like image 888
Ritienne Gauci Avatar asked Jan 17 '26 23:01

Ritienne Gauci


2 Answers

Yes, in MongoDB 4.2+ you can update it like this:

db.col.updateOne(
   { "_id": ObjectId("5e302f83edd1fd00125abbf9") },
   [
      { $set: { dateTransferred: { $add: ["$dateTransferred", 1000 * 60 * 60 * 24] } } }
   ]
)

Of course, if you like to update all documents then it would be

db.col.updateMany(
   {},
   [
      { $set: { dateTransferred: { $add: ["$dateTransferred", 1000 * 60 * 60 * 24] } } }
   ]
)
like image 188
Wernfried Domscheit Avatar answered Jan 20 '26 16:01

Wernfried Domscheit


No, you can not access values of record that is being updated using this simple notation.

You might want to try using the aggregation pipeline (limited to mongodb 4.2+) as described here: https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-with-aggregation-pipeline

So far, I haven't tried this myself, but looks promising ;-)

like image 41
Iľja Avatar answered Jan 20 '26 15:01

Iľja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!