Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any Equivalent of NOW() in MongoDB

Tags:

mongodb

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?

like image 917
Aysennoussi Avatar asked Dec 16 '13 20:12

Aysennoussi


People also ask

What is now in MongoDB?

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.

How does MongoDB match current date?

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.

How does MongoDB store time?

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.


1 Answers

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.

like image 116
Penny Liu Avatar answered Sep 19 '22 17:09

Penny Liu