$currentDate

Definition

Changed in version 3.0: MongoDB no longer treats the timestamp and the Date data types as equivalent forcomparison/sorting purposes. For details, seeDate and Timestamp Comparison Order.

The $currentDate operator has the form:

  1. { $currentDate: { <field1>: <typeSpecification1>, ... } }

<typeSpecification> can be either:

  • a boolean true to set the field value to the current date as aDate, or
  • a document { $type: "timestamp" } or { $type: "date" }which explicitly specifies the type. The operator iscase-sensitive and accepts only the lowercase "timestamp" orthe lowercase "date".To specify a <field> in an embedded document or in an array, usedot notation.

Behavior

If the field does not exist, $currentDate adds the field to adocument.

Example

Consider the following document in the users collection:

  1. { _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") }

The following operation updates the lastModified field to thecurrent date, the "cancellation.date" field to the current timestampas well as updating the status field to "D" and the"cancellation.reason" to "user request".

  1. db.users.update(
  2. { _id: 1 },
  3. {
  4. $currentDate: {
  5. lastModified: true,
  6. "cancellation.date": { $type: "timestamp" }
  7. },
  8. $set: {
  9. status: "D",
  10. "cancellation.reason": "user request"
  11. }
  12. }
  13. )

The updated document would resemble:

  1. {
  2. "_id" : 1,
  3. "status" : "D",
  4. "lastModified" : ISODate("2014-09-17T23:25:56.314Z"),
  5. "cancellation" : {
  6. "date" : Timestamp(1410996356, 1),
  7. "reason" : "user request"
  8. }
  9. }

See also

db.collection.update(),db.collection.findAndModify()