MongoDB $second Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $second?

$second is a MongoDB aggregation expression that returns the seconds portion of a date as an integer from 0 to 59 (rarely 60 for leap seconds). For …T08:15:39.736Z, the result is 39.

Remember
$second = seconds part of a date (0 … 59)

{ $second: <dateExpression> }

{ $second: { date: <date>, timezone: <tz> } }

ISODate("…T08:15:39.736Z") → 39
ISODate("…T12:01:00Z") → 0

null / missing → null
string date → pipeline error
UsePrefer
Seconds (0–59)$second
Minutes (0–59)$minute
Milliseconds (0–999)$millisecond

How to Use $second in MongoDB

Pass a BSON date field (or expression), optionally with a timezone.

  1. Choose an expression stage ($addFields or $project).
  2. Pass a Date / Timestamp / ObjectId expression to $second.
  3. Use the short form for UTC, or the document form with timezone when needed.
  4. Combine with $hour, $minute, or $millisecond to break a timestamp into parts.
PieceRequired?Role
$secondYesReturns seconds 0–59
Date expressionYesDate, Timestamp, or ObjectId
timezoneNoOlson id or UTC offset (default: UTC)

Pseudocode

Pseudocode
for each document:
    d = evaluate(dateExpression)
    if d is null or missing:
        result = null
    else if d is a string:
        error  // aggregation fails
    else:
        result = seconds part of d   // 0 … 59 (UTC or timezone)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while extracting seconds.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $second: <date> }
Range0 … 59 (rarely 60)
Input typesDate, Timestamp, ObjectId
Default zoneUTC
Sample…T08:15:39Z → 39
StringsNot allowed — convert first

Live Preview

Watch $second pull the 0–59 part from a timestamp (UTC).

Simulates $second in UTC (same idea as the mongosh examples below).

Result
date = 2014-01-01T08:15:39.736Z
$second → 39

{ seconds: 39 }

Worked Walkthrough — Sale Timestamp

A sale was recorded at 2014-01-01T08:15:39.736Z. We want only the seconds part.

Calculation
Document:
  { item: "abc", date: ISODate("2014-01-01T08:15:39.736Z") }

Break the time (UTC):
  hour   → 8
  minute → 15
  second → 39

$second("$date") → 39

Check: clock shows 08:15:39 → second is 39 ✓

MongoDB Examples

We use a small sales collection. First we extract seconds in UTC, then break the clock into hour / minute / second. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two sales with precise timestamps. We save them in a collection named sales.

mongosh
db.sales.insertMany([
  {
    _id: 1,
    item: "abc",
    price: 10,
    quantity: 2,
    date: ISODate("2014-01-01T08:15:39.736Z")
  },
  {
    _id: 2,
    item: "xyz",
    price: 20,
    quantity: 1,
    date: ISODate("2016-01-01T12:01:00.000Z")
  }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in sales. Run find() to see them:

mongosh
db.sales.find()

Read one document like this:

Field in MongoDBValue (doc 1)Plain English
_id1Document id
item"abc"Product code
date…T08:15:39.736ZSale time (BSON Date)

How It Works

  1. Insert once. insertMany adds two sale documents to sales.
  2. Dates are BSON Date. Use ISODate(...), not plain strings.
  3. find() shows the same shape. Ready for $second next.

Example 2 — Extract Seconds

Goal: read the 0–59 seconds portion of each sale’s date (UTC).

mongosh
db.sales.aggregate([
  {
    $addFields: {
      seconds: { $second: "$date" }
    }
  }
]);

How It Works

  1. Read the stored date. Document 1 has …T08:15:39.736Z.
  2. Extract seconds. $second: "$date" returns 39 (UTC).
  3. Second document. …T12:01:00Z → second 0.
  4. Keep all fields. $addFields adds seconds next to the original sale data.

Example 3 — Hour, Minute, Second

Same sales, but project the full clock parts together so you can see how $second fits next to hour and minute.

mongosh
db.sales.aggregate([
  {
    $project: {
      item: 1,
      hour: { $hour: "$date" },
      minute: { $minute: "$date" },
      second: { $second: "$date" }
    }
  }
]);

How It Works

  1. Same stored dates. Still using the two sales from Example 1.
  2. Split the clock. $hour, $minute, and $second each return one integer part (UTC).
  3. First sale. 08:15:39 → hour 8, minute 15, second 39.
  4. Second sale. 12:01:00 → hour 12, minute 1, second 0.

Edge Cases & Pitfalls

Check these before using $second in production pipelines.

type

No string dates

Passing "2014-01-01" fails. Store BSON Date, or convert with $toDate / $dateFromString first.

null

Null and missing become null

Missing fields return null, not an error. Handle them before math if nulls are invalid in your data.

leap

Leap seconds can return 60

The normal range is 0–59, but MongoDB can return 60 to account for leap seconds. Do not assume the max is always 59 in strict validators.

vs

Don’t confuse with $minute / $millisecond

For …T08:15:39.736Z, minute is 15, second is 39, millisecond is 736. Use the operator that matches the part you need.

Performance Notes

ApproachCostBest for
$second alonePer-document date mathNeed only the seconds part
Several date partsStill O(docs)Hour / minute / second reports
+ timezoneSmall extra conversionLocal calendar views

Date-part expressions are cheap compared with large sorts or joins. Filter early with $match when only some documents need the seconds value.

Key Takeaways

  • Role: date → seconds 0–59.
  • Input: Date / Timestamp / ObjectId (not strings).
  • Sample: …T08:15:39Z → 39.
  • Family: pair with $hour, $minute, $millisecond.

One line: $second answers “what is the 0–59 seconds part of this date?”—in aggregation.

Frequently Asked Questions

$second returns an integer from 0 to 59 for the seconds portion of a date (rarely 60 for leap seconds). For ISODate("…T08:15:39.736Z"), it returns 39. Use it inside aggregation stages such as $project and $addFields.
Simple form: { $second: <dateExpression> }. With timezone: { $second: { date: <dateExpression>, timezone: <tz> } }. The date must be a Date, Timestamp, or ObjectId—not a string.
By default, $second uses UTC. Pass timezone (Olson name or UTC offset) when you need the second in another zone. Ordinary offsets usually leave the second value unchanged.
No. Convert strings to dates first (for example with $dateFromString or $toDate), then pass that date to $second.
$minute returns 0–59 for the minute. $second returns 0–59 for the second. $millisecond returns 0–999 for the fraction of the second.
Yes for the default UTC behavior. Think of $second as MongoDB’s aggregation version of Date.getUTCSeconds—unless you set timezone.

Next: $setDifference

Return the elements of the first array that are not in the second.

$setDifference tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful