$second (aggregation)

Definition

  • $second
  • Returns the second portion of a date as a number between 0 and 59,but can be 60 to account for leap seconds.

The $second expression has the followingoperator expression syntax:

  1. { $second: <dateExpression> }

Changed in version 3.6.

The argument must be a valid expression that resolves to one of the following:

New in version 3.6.

  1. { date: <dateExpression>, timezone: <tzExpression> }

FieldDescriptiondateThe date to which the operator is applied.<dateExpression> must be a valid expression that resolves to aDate, aTimestamp,or an ObjectID.timezoneOptional. The timezone of the operation result.<tzExpression> must be a valid expression that resolves to a string formatted as eitheran Olson Timezone Identifier or aUTC Offset.If no timezone is provided, the result is displayed in UTC.

FormatExamplesOlson Timezone Identifier

  1. "America/New_York"
  2. "Europe/London"
  3. "GMT"

UTC Offset

  1. +/-[hh]:[mm], e.g. "+04:45"
  2. +/-[hh][mm], e.g. "-0530"
  3. +/-[hh], e.g. "+03"

Behavior

ExampleResult
  1. { $second: new Date("2012-11-06T00:14:20") }
20
  1. { $second: { date: new Date("Jan 7, 2003") } }
0
  1. { $second: { date: new Date("August 14, 2011"), timezone: "America/Chicago"} }
0
  1. { $second: ISODate("1998-11-07T00:00:42Z") }
42
  1. { $second: { date: ISODate("1998-11-07T00:00:09Z"), timezone: "+0530"} }
9
  1. { $second: "March 28, 1976" }
error
  1. { $second: Date("2016-01-01") }
error
  1. { $second: "2009-04-09" }
error

Note

$second cannot take a string as an argument.

Example

Consider a sales collection with the following document:

  1. {
  2. "_id" : 1,
  3. "item" : "abc",
  4. "price" : 10,
  5. "quantity" : 2,
  6. "date" : ISODate("2014-01-01T08:15:39.736Z")
  7. }

The following aggregation uses the $second and other dateexpressions to break down the date field:

  1. db.sales.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. year: { $year: "$date" },
  7. month: { $month: "$date" },
  8. day: { $dayOfMonth: "$date" },
  9. hour: { $hour: "$date" },
  10. minutes: { $minute: "$date" },
  11. seconds: { $second: "$date" },
  12. milliseconds: { $millisecond: "$date" },
  13. dayOfYear: { $dayOfYear: "$date" },
  14. dayOfWeek: { $dayOfWeek: "$date" },
  15. week: { $week: "$date" }
  16. }
  17. }
  18. ]
  19. )

The operation returns the following result:

  1. {
  2. "_id" : 1,
  3. "year" : 2014,
  4. "month" : 1,
  5. "day" : 1,
  6. "hour" : 8,
  7. "minutes" : 15,
  8. "seconds" : 39,
  9. "milliseconds" : 736,
  10. "dayOfYear" : 1,
  11. "dayOfWeek" : 4,
  12. "week" : 0
  13. }