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)
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] } } }
]
)
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With