MongoDB $second Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Date Operations

What You’ll Learn

The $second operator extracts the seconds portion (0–59) from a BSON Date inside MongoDB aggregation pipelines. Use it for log timing analysis, sub-minute patterns, latency bucketing, and precise time breakdowns.

01

Extract Seconds

Date → 0–59.

02

Syntax

One date argument.

03

Timezone Option

Local second support.

04

UTC Default

0–59 in UTC.

05

Use Cases

Logs, bursts, timing.

06

Related Ops

$minute, $millisecond.

Definition and Usage

In MongoDB’s aggregation framework, the $second operator takes a date expression and returns an integer between 0 and 59. For example, $second applied to ISODate("2024-06-15T14:30:45Z") returns 45, and ISODate("2024-06-15T09:05:07Z") returns 7.

Seconds sit between $minute and $millisecond in MongoDB’s date-extraction family. Together with $hour and $minute, they let you break any timestamp into readable parts for filtering, grouping, or display.

💡
Beginner Tip

$second uses UTC by default. For log analysis in local time, use the object form with a timezone option (see Example 4).

📝 Syntax

The $second operator takes a date expression, or an object with date and timezone:

mongosh
{ $second: <dateExpression> }

// With timezone:
{
  $second: {
    date: <dateExpression>,
    timezone: <tz>
  }
}

Syntax Rules

  • Argument — any expression that evaluates to a BSON Date (field, $$NOW, or literal).
  • Return value — integer from 0 to 59 (seconds within the minute).
  • Null input — returns null when the date is null or missing.
  • Timezone — optional; use Olson timezone IDs like "Europe/London".
  • Use inside $project, $addFields, $set, $match (with $expr), or $group.

💡 $second vs $minute vs $millisecond

14:30:45.123Z$minute: 30, $second: 45, $millisecond: 123
$second — BSON Date → integer 0–59 (second component)
$dateTrunc — BSON Date → Date at period boundary (better for bucketing than single components)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date extraction)
ArgumentsOne date expression
Return typeInteger (0–59)
Timezone supportYes (object form with timezone)
MongoDB version3.4+
From field
{ $second: "$loggedAt" }

Second component

14:30:45 UTC
{
  $second: ISODate("2024-06-15T14:30:45Z")
}

Returns 45

In $project
{
  sec: { $second: "$eventAt" }
}

Add computed field

With timezone
{
  $second: {
    date: "$eventAt",
    timezone: "Asia/Tokyo"
  }
}

Local second

Examples Gallery

Extract seconds from log timestamps, find events at the start of a minute, group request bursts by second, and read seconds in a local timezone.

📚 Request Log Analysis

Use a requests collection and extract seconds from loggedAt.

Sample Input Documents

Suppose you have a requests collection with timestamps:

mongosh
[
  {
    "_id": 1,
    "path": "/api/users",
    "loggedAt": ISODate("2024-06-15T14:30:45Z")
  },
  {
    "_id": 2,
    "path": "/api/orders",
    "loggedAt": ISODate("2024-06-15T09:05:07Z")
  },
  {
    "_id": 3,
    "path": "/health",
    "loggedAt": ISODate("2024-06-15T10:00:00Z")
  }
]

Example 1 — Add second with $second

Extract the seconds component from each log timestamp:

mongosh
db.requests.aggregate([
  {
    $project: {
      path: 1,
      loggedAt: 1,
      second: { $second: "$loggedAt" }
    }
  }
])

How It Works

  • 14:30:45 UTC → second 45.
  • 09:05:07 UTC → second 7.
  • 10:00:00 UTC → second 0 (start of the minute).

📈 Practical Patterns

Sub-minute filters, burst grouping, and timezone-aware extraction.

Example 2 — Find Events at the Start of a Minute

Match records logged exactly when the second is 0:

mongosh
db.requests.find({
  $expr: {
    $eq: [
      { $second: "$loggedAt" },
      0
    ]
  }
})

How It Works

Combine $second with $eq inside $expr. Useful for cron-aligned jobs, heartbeat checks, or events that fire on the minute boundary.

Example 3 — Group Requests by Second Within the Minute

See which second marks see the most traffic (across all hours and days):

mongosh
db.requests.aggregate([
  {
    $group: {
      _id: { $second: "$loggedAt" },
      count: { $sum: 1 }
    }
  },
  { $sort: { "_id": 1 } }
])

How It Works

Grouping by $second reveals sub-minute burst patterns. Pair with $minute and $hour in the _id if you need a full time breakdown.

Example 4 — Second in a Specific Timezone

Extract the second in Pacific Time rather than UTC:

mongosh
db.requests.aggregate([
  {
    $project: {
      path: 1,
      loggedAt: 1,
      secondUtc: { $second: "$loggedAt" },
      secondPacific: {
        $second: {
          date: "$loggedAt",
          timezone: "America/Los_Angeles"
        }
      }
    }
  }
])

// loggedAt: 2024-06-15T14:30:45Z
// secondUtc: 45; secondPacific may differ near zone boundaries

How It Works

The object form with timezone converts the instant to the specified zone before extracting the second. UTC and local values can differ when the local minute boundary does not align with UTC.

Bonus — Full H:M:S Breakdown

Build a readable time-of-day string from hour, minute, and second:

mongosh
db.requests.aggregate([
  {
    $project: {
      path: 1,
      loggedAt: 1,
      timeParts: {
        hour: { $hour: "$loggedAt" },
        minute: { $minute: "$loggedAt" },
        second: { $second: "$loggedAt" }
      }
    }
  }
])

// 14:30:45 UTC → { hour: 14, minute: 30, second: 45 }

How It Works

Combine $hour, $minute, and $second for a complete clock-time breakdown. Add $millisecond when you need sub-second precision.

🚀 Use Cases

  • Log timing — analyze when within each minute events occur.
  • Sub-minute bursts — group high-frequency data by second for spike detection.
  • Cron alignment — find jobs or heartbeats that fire at second 0.
  • Time breakdowns — combine with $hour and $minute for display or reporting.

🧠 How $second Works

1

MongoDB resolves the date

The expression evaluates to a BSON Date (or null).

Input
2

Timezone is applied if provided

With timezone, the instant is interpreted in that zone before extraction.

Timezone
3

The second component is extracted

MongoDB returns an integer from 0 to 59 representing seconds within the minute.

Extract
=

Integer 0–59

Use in projections, filters, or group keys for time-based analysis.

Conclusion

The $second operator extracts the seconds portion (0–59) from a BSON Date in MongoDB aggregation pipelines. It is a building block for log analysis, sub-minute grouping, and precise time breakdowns alongside $hour and $minute.

Remember: UTC by default, optional timezone for local time, and null when the date is missing. Next in the series: $setDifference.

💡 Best Practices

✅ Do

  • Use timezone when reporting in local business hours
  • Combine with $hour and $minute for full clock breakdowns
  • Use $millisecond when sub-second precision matters
  • Handle null dates with $ifNull in downstream logic
  • Use $dateTrunc for time bucketing instead of many components

❌ Don’t

  • Assume UTC seconds match local seconds without checking timezone
  • Use $second on string dates — convert with $toDate first
  • Forget that grouping by second alone merges all hours and days
  • Confuse $second with elapsed duration (use date arithmetic instead)
  • Expect fractional seconds — use $millisecond for that

Key Takeaways

Knowledge Unlocked

Five things to remember about $second

Use these points when extracting seconds from dates in MongoDB.

5
Core concepts
📝 02

One date arg

Field or ISODate.

Syntax
🛠 03

UTC default

timezone optional.

Timezone
🔄 04

Date family

$minute, $hour.

Related
📑 05

Log analysis

Bursts & timing.

Use case

❓ Frequently Asked Questions

$second returns an integer from 0 to 59 representing the seconds portion of a BSON Date. For example, 14:30:45 UTC returns 45, and 9:05:07 UTC returns 7.
Simple form: { $second: <dateExpression> }. With timezone: { $second: { date: <dateExpression>, timezone: <tz> } }. Pass a field like "$loggedAt" or a literal ISODate.
By default, $second uses UTC. To get the second in a specific timezone, use the object form with a timezone string like "America/Los_Angeles".
$second returns 0–59 (seconds within the minute). $minute returns 0–59 (minutes within the hour). $millisecond returns 0–999 (fractional part of the second).
$second is available in MongoDB 3.4 and later in aggregation pipelines and update pipelines that use aggregation expressions.

Continue the Operator Series

Move on to $setDifference for set operations, or review $minute for the minute component.

Next: $setDifference →

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.

5 people found this page helpful