I am trying to migrate from MySQL to MongoDB and want to insert the current date as I do with NOW()
in MySQL. Does anyone know a 1 line solution or should I do it with PHP?
MongoDB provides the NOW system variable that allows you to get the current datetime value when using an aggregation pipeline. This can be useful for when you want to update a document with the current datetime. Starting in MongoDB 4.2, update methods can can accept an aggregation pipeline.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.
For new features in MongoDB 4.2
. You can use NOW to get the current datetime value.
Use Case: to access the variable, prefix with
$$
and enclose in quotes.
db.students.updateOne( { _id: 3 }, [ { $set: { "test3": 98, modified: "$$NOW"} } ] )
Moreover, The CLUSTER_TIME will return the current timestamp value but is only available on replica sets and sharded clusters.
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